Rename Red Knot (#17820)

This commit is contained in:
Micha Reiser 2025-05-03 19:49:15 +02:00 committed by GitHub
parent e6a798b962
commit b51c4f82ea
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
1564 changed files with 1598 additions and 1578 deletions

4
crates/ty_vendored/.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
# Do not ignore any of the vendored files. If this pattern is not present,
# we will gitignore the `venv/` stubs in typeshed, as there is a general
# rule to ignore `venv/` directories in the root `.gitignore`.
!/vendor/typeshed/**/*

View file

@ -0,0 +1,31 @@
[package]
name = "ty_vendored"
version = "0.0.0"
publish = false
authors = { workspace = true }
edition = { workspace = true }
rust-version = { workspace = true }
homepage = { workspace = true }
documentation = { workspace = true }
repository = { workspace = true }
license = { workspace = true }
[dependencies]
ruff_db = { workspace = true }
zip = { workspace = true }
[build-dependencies]
path-slash = { workspace = true }
walkdir = { workspace = true }
zip = { workspace = true, features = ["zstd", "deflate"] }
[dev-dependencies]
walkdir = { workspace = true }
[features]
zstd = ["zip/zstd"]
deflate = ["zip/deflate"]
[lints]
workspace = true

View file

@ -0,0 +1,5 @@
# Vendored types for the stdlib
This crate vendors [typeshed](https://github.com/python/typeshed)'s stubs for the standard library. The vendored stubs can be found in `crates/ty_vendored/vendor/typeshed`. The file `crates/ty_vendored/vendor/typeshed/source_commit.txt` tells you the typeshed commit that our vendored stdlib stubs currently correspond to.
The typeshed stubs are updated every two weeks via an automated PR using the `sync_typeshed.yaml` workflow in the `.github/workflows` directory. This workflow can also be triggered at any time via [workflow dispatch](https://docs.github.com/en/actions/using-workflows/manually-running-a-workflow#running-a-workflow).

103
crates/ty_vendored/build.rs Normal file
View file

@ -0,0 +1,103 @@
//! Build script to package our vendored typeshed files
//! into a zip archive that can be included in the Ruff binary.
//!
//! This script should be automatically run at build time
//! whenever the script itself changes, or whenever any files
//! in `crates/ty_vendored/vendor/typeshed` change.
use std::fs::File;
use std::io::Write;
use std::path::Path;
use path_slash::PathExt;
use zip::result::ZipResult;
use zip::write::{FileOptions, ZipWriter};
use zip::CompressionMethod;
const TYPESHED_SOURCE_DIR: &str = "vendor/typeshed";
const TY_EXTENSIONS_STUBS: &str = "ty_extensions/ty_extensions.pyi";
const TYPESHED_ZIP_LOCATION: &str = "/zipped_typeshed.zip";
/// Recursively zip the contents of the entire typeshed directory and patch typeshed
/// on the fly to include the `ty_extensions` module.
///
/// This routine is adapted from a recipe at
/// <https://github.com/zip-rs/zip-old/blob/5d0f198124946b7be4e5969719a7f29f363118cd/examples/write_dir.rs>
fn write_zipped_typeshed_to(writer: File) -> ZipResult<File> {
let mut zip = ZipWriter::new(writer);
// Use deflated compression for WASM builds because compiling `zstd-sys` requires clang
// [source](https://github.com/gyscos/zstd-rs/wiki/Compile-for-WASM) which complicates the build
// by a lot. Deflated compression is slower but it shouldn't matter much for the WASM use case
// (WASM itself is already slower than a native build for a specific platform).
// We can't use `#[cfg(...)]` here because the target-arch in a build script is the
// architecture of the system running the build script and not the architecture of the build-target.
// That's why we use the `TARGET` environment variable here.
let method = if cfg!(feature = "zstd") {
CompressionMethod::Zstd
} else if cfg!(feature = "deflate") {
CompressionMethod::Deflated
} else {
CompressionMethod::Stored
};
let options = FileOptions::default()
.compression_method(method)
.unix_permissions(0o644);
for entry in walkdir::WalkDir::new(TYPESHED_SOURCE_DIR) {
let dir_entry = entry.unwrap();
let absolute_path = dir_entry.path();
let normalized_relative_path = absolute_path
.strip_prefix(Path::new(TYPESHED_SOURCE_DIR))
.unwrap()
.to_slash()
.expect("Unexpected non-utf8 typeshed path!");
// Write file or directory explicitly
// Some unzip tools unzip files with directory paths correctly, some do not!
if absolute_path.is_file() {
println!("adding file {absolute_path:?} as {normalized_relative_path:?} ...");
zip.start_file(&*normalized_relative_path, options)?;
let mut f = File::open(absolute_path)?;
std::io::copy(&mut f, &mut zip).unwrap();
// Patch the VERSIONS file to make `ty_extensions` available
if normalized_relative_path == "stdlib/VERSIONS" {
writeln!(&mut zip, "ty_extensions: 3.0-")?;
}
} else if !normalized_relative_path.is_empty() {
// Only if not root! Avoids path spec / warning
// and mapname conversion failed error on unzip
println!("adding dir {absolute_path:?} as {normalized_relative_path:?} ...");
zip.add_directory(normalized_relative_path, options)?;
}
}
// Patch typeshed and add the stubs for the `ty_extensions` module
println!("adding file {TY_EXTENSIONS_STUBS} as stdlib/ty_extensions.pyi ...");
zip.start_file("stdlib/ty_extensions.pyi", options)?;
let mut f = File::open(TY_EXTENSIONS_STUBS)?;
std::io::copy(&mut f, &mut zip).unwrap();
zip.finish()
}
fn main() {
assert!(
Path::new(TYPESHED_SOURCE_DIR).is_dir(),
"Where is typeshed?"
);
let out_dir = std::env::var("OUT_DIR").unwrap();
// N.B. Deliberately using `format!()` instead of `Path::join()` here,
// so that we use `/` as a path separator on all platforms.
// That enables us to load the typeshed zip at compile time in `module.rs`
// (otherwise we'd have to dynamically determine the exact path to the typeshed zip
// based on the default path separator for the specific platform we're on,
// which can't be done at compile time.)
let zipped_typeshed_location = format!("{out_dir}{TYPESHED_ZIP_LOCATION}");
let zipped_typeshed_file = File::create(zipped_typeshed_location).unwrap();
write_zipped_typeshed_to(zipped_typeshed_file).unwrap();
}

View file

@ -0,0 +1,98 @@
use ruff_db::vendored::VendoredFileSystem;
use std::sync::LazyLock;
// The file path here is hardcoded in this crate's `build.rs` script.
// Luckily this crate will fail to build if this file isn't available at build time.
static TYPESHED_ZIP_BYTES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/zipped_typeshed.zip"));
pub fn file_system() -> &'static VendoredFileSystem {
static VENDORED_TYPESHED_STUBS: LazyLock<VendoredFileSystem> =
LazyLock::new(|| VendoredFileSystem::new_static(TYPESHED_ZIP_BYTES).unwrap());
&VENDORED_TYPESHED_STUBS
}
#[cfg(test)]
mod tests {
use std::io::{self, Read};
use std::path::Path;
use ruff_db::vendored::VendoredPath;
use super::*;
#[test]
fn typeshed_zip_created_at_build_time() {
let mut typeshed_zip_archive =
zip::ZipArchive::new(io::Cursor::new(TYPESHED_ZIP_BYTES)).unwrap();
let mut functools_module_stub = typeshed_zip_archive
.by_name("stdlib/functools.pyi")
.unwrap();
assert!(functools_module_stub.is_file());
let mut functools_module_stub_source = String::new();
functools_module_stub
.read_to_string(&mut functools_module_stub_source)
.unwrap();
assert!(functools_module_stub_source.contains("def update_wrapper("));
}
#[test]
fn typeshed_vfs_consistent_with_vendored_stubs() {
let vendored_typeshed_dir = Path::new("vendor/typeshed").canonicalize().unwrap();
let vendored_typeshed_stubs = file_system();
let mut empty_iterator = true;
for entry in walkdir::WalkDir::new(&vendored_typeshed_dir).min_depth(1) {
empty_iterator = false;
let entry = entry.unwrap();
let absolute_path = entry.path();
let file_type = entry.file_type();
let relative_path = absolute_path
.strip_prefix(&vendored_typeshed_dir)
.unwrap_or_else(|_| {
panic!("Expected {absolute_path:?} to be a child of {vendored_typeshed_dir:?}")
});
let vendored_path = <&VendoredPath>::try_from(relative_path)
.unwrap_or_else(|_| panic!("Expected {relative_path:?} to be valid UTF-8"));
assert!(
vendored_typeshed_stubs.exists(vendored_path),
"Expected {vendored_path:?} to exist in the `VendoredFileSystem`!
Vendored file system:
{vendored_typeshed_stubs:#?}
"
);
let vendored_path_kind = vendored_typeshed_stubs
.metadata(vendored_path)
.unwrap_or_else(|_| {
panic!(
"Expected metadata for {vendored_path:?} to be retrievable from the `VendoredFileSystem!
Vendored file system:
{vendored_typeshed_stubs:#?}
"
)
})
.kind();
assert_eq!(
vendored_path_kind.is_directory(),
file_type.is_dir(),
"{vendored_path:?} had type {vendored_path_kind:?}, inconsistent with fs path {relative_path:?}: {file_type:?}"
);
}
assert!(
!empty_iterator,
"Expected there to be at least one file or directory in the vendored typeshed stubs!"
);
}
}

View file

@ -0,0 +1,2 @@
The `build.rs` copies the `ty_extensions.pyi` file in this directory into
the `vendor/typeshed/stdlib` directory.

View file

@ -0,0 +1,32 @@
from typing import Any, LiteralString, _SpecialForm
# Special operations
def static_assert(condition: object, msg: LiteralString | None = None) -> None: ...
# Types
Unknown = object()
AlwaysTruthy = object()
AlwaysFalsy = object()
# Special forms
Not: _SpecialForm
Intersection: _SpecialForm
TypeOf: _SpecialForm
CallableTypeOf: _SpecialForm
# Predicates on types
#
# Ideally, these would be annotated using `TypeForm`, but that has not been
# standardized yet (https://peps.python.org/pep-0747).
def is_equivalent_to(type_a: Any, type_b: Any) -> bool: ...
def is_subtype_of(type_derived: Any, type_base: Any) -> bool: ...
def is_assignable_to(type_target: Any, type_source: Any) -> bool: ...
def is_disjoint_from(type_a: Any, type_b: Any) -> bool: ...
def is_gradual_equivalent_to(type_a: Any, type_b: Any) -> bool: ...
def is_fully_static(type: Any) -> bool: ...
def is_singleton(type: Any) -> bool: ...
def is_single_valued(type: Any) -> bool: ...
# Returns the generic context of a type as a tuple of typevars, or `None` if the
# type is not generic.
def generic_context(type: Any) -> Any: ...

View file

@ -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.
= = = = =

View file

@ -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 as 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.9 to 3.13.
## Using
If you're just using a type checker ([mypy](https://github.com/python/mypy/),
[pyright](https://github.com/microsoft/pyright),
[pytype](https://github.com/google/pytype/), PyCharm, ...), as opposed to
developing it, you don't need to interact with the typeshed repo at
all: a copy of 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 [PEP 561](http://www.python.org/dev/peps/pep-0561/)
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 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.

View file

@ -0,0 +1 @@
eec809d049d10a5ae9b88780eab15fe36a9768d7

View file

@ -0,0 +1,339 @@
# 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-
_bootlocale: 3.4-3.9
_bz2: 3.3-
_codecs: 3.0-
_collections_abc: 3.3-
_compat_pickle: 3.1-
_compression: 3.5-
_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-
_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-
abc: 3.0-
aifc: 3.0-3.12
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.mixins: 3.10-
asyncio.runners: 3.7-
asyncio.staggered: 3.8-
asyncio.taskgroups: 3.11-
asyncio.threads: 3.9-
asyncio.timeouts: 3.11-
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-
concurrent: 3.2-
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
distutils.command.bdist_wininst: 3.0-3.9
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-
formatter: 3.0-3.9
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-
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
parser: 3.0-3.9
pathlib: 3.4-
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-
pstats: 3.0-
pty: 3.0-
pwd: 3.0-
py_compile: 3.0-
pyclbr: 3.0-
pydoc: 3.0-
pydoc_data: 3.0-
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-
sre_constants: 3.0-
sre_parse: 3.0-
ssl: 3.0-
stat: 3.0-
statistics: 3.4-
string: 3.0-
stringprep: 3.0-
struct: 3.0-
subprocess: 3.0-
sunau: 3.0-3.12
symbol: 3.0-3.9
symtable: 3.0-
sys: 3.0-
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-
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-

View file

@ -0,0 +1,36 @@
from typing_extensions 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",
]

View file

@ -0,0 +1,3 @@
from typing import Any
def __getattr__(name: str) -> Any: ...

View file

@ -0,0 +1,138 @@
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,
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,
mod as mod,
operator as operator,
stmt as stmt,
type_ignore as type_ignore,
unaryop as unaryop,
withitem as withitem,
)
from typing import Literal
if sys.version_info >= (3, 12):
from ast import ParamSpec as ParamSpec, TypeVar as TypeVar, TypeVarTuple as TypeVarTuple, type_param as type_param
if sys.version_info >= (3, 11):
from ast import TryStar as TryStar
if sys.version_info >= (3, 10):
from ast import (
MatchAs as MatchAs,
MatchClass as MatchClass,
MatchMapping as MatchMapping,
MatchOr as MatchOr,
MatchSequence as MatchSequence,
MatchSingleton as MatchSingleton,
MatchStar as MatchStar,
MatchValue as MatchValue,
match_case as match_case,
pattern as pattern,
)
PyCF_ALLOW_TOP_LEVEL_AWAIT: Literal[8192]
PyCF_ONLY_AST: Literal[1024]
PyCF_TYPE_COMMENTS: Literal[4096]
if sys.version_info >= (3, 13):
PyCF_OPTIMIZED_AST: Literal[33792]

View file

@ -0,0 +1,105 @@
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, TypeVar
from typing_extensions import Self, TypeAlias
_T = TypeVar("_T")
_T_co = TypeVar("_T_co", covariant=True)
_TaskYieldType: TypeAlias = Future[object] | None
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: ...
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.
class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments]
if sys.version_info >= (3, 12):
def __init__(
self,
coro: _TaskCompatibleCoro[_T_co],
*,
loop: AbstractEventLoop | None = None,
name: str | 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 = ...,
context: Context | None = None,
) -> None: ...
else:
def __init__(
self, coro: _TaskCompatibleCoro[_T_co], *, loop: AbstractEventLoop | None = None, name: str | 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: ...
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: ...

View file

@ -0,0 +1,84 @@
import sys
from _typeshed import SupportsLenAndGetItem, SupportsRichComparisonT
from collections.abc import Callable, MutableSequence
from typing import TypeVar, overload
_T = TypeVar("_T")
if sys.version_info >= (3, 10):
@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: SupportsLenAndGetItem[_T],
x: SupportsRichComparisonT,
lo: int = 0,
hi: int | None = None,
*,
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: SupportsLenAndGetItem[_T],
x: SupportsRichComparisonT,
lo: int = 0,
hi: int | None = None,
*,
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: ...
else:
def bisect_left(
a: SupportsLenAndGetItem[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None
) -> int: ...
def bisect_right(
a: SupportsLenAndGetItem[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None
) -> int: ...
def insort_left(
a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None
) -> None: ...
def insort_right(
a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None
) -> None: ...

View file

@ -0,0 +1,76 @@
from _typeshed import ReadableBuffer
from typing import ClassVar, final
from typing_extensions import Self
BLAKE2B_MAX_DIGEST_SIZE: int = 64
BLAKE2B_MAX_KEY_SIZE: int = 64
BLAKE2B_PERSON_SIZE: int = 16
BLAKE2B_SALT_SIZE: int = 16
BLAKE2S_MAX_DIGEST_SIZE: int = 32
BLAKE2S_MAX_KEY_SIZE: int = 32
BLAKE2S_PERSON_SIZE: int = 8
BLAKE2S_SALT_SIZE: int = 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
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
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: ...

View file

@ -0,0 +1 @@
def getpreferredencoding(do_setlocale: bool = True) -> str: ...

View file

@ -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: ...

View file

@ -0,0 +1,122 @@
import codecs
import sys
from _typeshed import ReadableBuffer
from collections.abc import Callable
from typing import Literal, final, overload, type_check_only
from typing_extensions import TypeAlias
# 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: ...
if sys.version_info >= (3, 10):
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]: ...
def escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, 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]: ...

View file

@ -0,0 +1,107 @@
import sys
from abc import abstractmethod
from types import MappingProxyType
from typing import ( # noqa: Y022,Y038,UP035
AbstractSet as Set,
AsyncGenerator as AsyncGenerator,
AsyncIterable as AsyncIterable,
AsyncIterator as AsyncIterator,
Awaitable as Awaitable,
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, 14):
from typing import ByteString as ByteString # noqa: Y057,UP035
__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: ...
if sys.version_info >= (3, 10):
@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]: ...
if sys.version_info >= (3, 10):
@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: ...
if sys.version_info >= (3, 10):
@property
def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ...
if sys.version_info >= (3, 12):
@runtime_checkable
class Buffer(Protocol):
@abstractmethod
def __buffer__(self, flags: int, /) -> memoryview: ...

View file

@ -0,0 +1,8 @@
IMPORT_MAPPING: dict[str, str]
NAME_MAPPING: dict[tuple[str, str], tuple[str, str]]
PYTHON2_EXCEPTIONS: tuple[str, ...]
MULTIPROCESSING_EXCEPTIONS: tuple[str, ...]
REVERSE_IMPORT_MAPPING: dict[str, str]
REVERSE_NAME_MAPPING: dict[tuple[str, str], tuple[str, str]]
PYTHON3_OSERROR_EXCEPTIONS: tuple[str, ...]
PYTHON3_IMPORTERROR_EXCEPTIONS: tuple[str, ...]

View file

@ -0,0 +1,25 @@
from _typeshed import WriteableBuffer
from collections.abc import Callable
from io import DEFAULT_BUFFER_SIZE, BufferedIOBase, RawIOBase
from typing import Any, Protocol
BUFFER_SIZE = DEFAULT_BUFFER_SIZE
class _Reader(Protocol):
def read(self, n: int, /) -> bytes: ...
def seekable(self) -> bool: ...
def seek(self, n: int, /) -> Any: ...
class BaseStream(BufferedIOBase): ...
class DecompressReader(RawIOBase):
def __init__(
self,
fp: _Reader,
decomp_factory: Callable[..., object],
trailing_error: type[Exception] | tuple[type[Exception], ...] = (),
**decomp_args: Any,
) -> None: ...
def readinto(self, b: WriteableBuffer) -> int: ...
def read(self, size: int = -1) -> bytes: ...
def seek(self, offset: int, whence: int = 0) -> int: ...

View file

@ -0,0 +1,58 @@
from collections.abc import Callable, Iterator, Mapping
from types import GenericAlias
from typing import Any, ClassVar, Generic, TypeVar, final, overload
from typing_extensions import ParamSpec, 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: ...
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: ...

View file

@ -0,0 +1,132 @@
import csv
import sys
from _typeshed import SupportsWrite
from collections.abc import Iterable
from typing import Any, Final, type_check_only
from typing_extensions import Self, TypeAlias
__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
# Ideally this would be `QUOTE_ALL | QUOTE_MINIMAL | QUOTE_NONE | QUOTE_NONNUMERIC`
# However, using literals in situations like these can cause false-positives (see #7258)
_QuotingType: TypeAlias = int
class Error(Exception): ...
_DialectLike: TypeAlias = str | Dialect | csv.Dialect | type[Dialect | csv.Dialect]
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 = ...,
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: ...
if sys.version_info >= (3, 10):
# This class calls itself _csv.reader.
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.
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: ...
# For the return types below.
# These aliases can be removed when typeshed drops support for 3.9.
_reader = Reader
_writer = Writer
else:
# This class is not exposed. It calls itself _csv.reader.
@type_check_only
class _reader:
@property
def dialect(self) -> Dialect: ...
line_num: int
def __iter__(self) -> Self: ...
def __next__(self) -> list[str]: ...
# This class is not exposed. It calls itself _csv.writer.
@type_check_only
class _writer:
@property
def dialect(self) -> Dialect: ...
def writerow(self, row: Iterable[Any]) -> Any: ...
def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ...
def writer(
csvfile: 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(
csvfile: 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] = ...,
*,
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: ...

View file

@ -0,0 +1,331 @@
import _typeshed
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, Generic, TypeVar, final, overload, type_check_only
from typing_extensions import Self, TypeAlias
_T = TypeVar("_T")
_CT = TypeVar("_CT", bound=_CData)
FUNCFLAG_CDECL: int
FUNCFLAG_PYTHONAPI: int
FUNCFLAG_USE_ERRNO: int
FUNCFLAG_USE_LASTERROR: int
RTLD_GLOBAL: int
RTLD_LOCAL: int
if sys.version_info >= (3, 11):
CTYPES_MAX_ARGCOUNT: int
if sys.version_info >= (3, 12):
SIZEOF_TIME_T: 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: int
FUNCFLAG_STDCALL: int
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: ...
# 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]
class _CanCastTo(_CData): ...
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: Any, /) -> 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, /) -> list[Any]: ...
def __setitem__(self, key: int, value: Any, /) -> None: ...
@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: ...
def byref(obj: _CData | _CDataType, offset: int = ...) -> _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")
# This class is not exposed. It calls itself _ctypes.CField.
@final
@type_check_only
class _CField(Generic[_CT, _GetT, _SetT]):
offset: int
size: int
if sys.version_info >= (3, 10):
@overload
def __get__(self, instance: None, owner: type[Any] | None = None, /) -> Self: ...
@overload
def __get__(self, instance: Any, owner: type[Any] | None = None, /) -> _GetT: ...
else:
@overload
def __get__(self, instance: None, owner: type[Any] | None, /) -> Self: ...
@overload
def __get__(self, instance: Any, owner: type[Any] | 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]
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, /) -> list[Any]: ...
@overload
def __setitem__(self, key: int, value: Any, /) -> None: ...
@overload
def __setitem__(self, key: slice, 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: ...

View file

@ -0,0 +1,548 @@
import sys
from _typeshed import ReadOnlyBuffer, SupportsRead, SupportsWrite
from curses import _ncurses_version
from typing import Any, final, overload
from typing_extensions import TypeAlias
# 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: int
ACS_BLOCK: int
ACS_BOARD: int
ACS_BSBS: int
ACS_BSSB: int
ACS_BSSS: int
ACS_BTEE: int
ACS_BULLET: int
ACS_CKBOARD: int
ACS_DARROW: int
ACS_DEGREE: int
ACS_DIAMOND: int
ACS_GEQUAL: int
ACS_HLINE: int
ACS_LANTERN: int
ACS_LARROW: int
ACS_LEQUAL: int
ACS_LLCORNER: int
ACS_LRCORNER: int
ACS_LTEE: int
ACS_NEQUAL: int
ACS_PI: int
ACS_PLMINUS: int
ACS_PLUS: int
ACS_RARROW: int
ACS_RTEE: int
ACS_S1: int
ACS_S3: int
ACS_S7: int
ACS_S9: int
ACS_SBBS: int
ACS_SBSB: int
ACS_SBSS: int
ACS_SSBB: int
ACS_SSBS: int
ACS_SSSB: int
ACS_SSSS: int
ACS_STERLING: int
ACS_TTEE: int
ACS_UARROW: int
ACS_ULCORNER: int
ACS_URCORNER: int
ACS_VLINE: int
ALL_MOUSE_EVENTS: int
A_ALTCHARSET: int
A_ATTRIBUTES: int
A_BLINK: int
A_BOLD: int
A_CHARTEXT: int
A_COLOR: int
A_DIM: int
A_HORIZONTAL: int
A_INVIS: int
A_ITALIC: int
A_LEFT: int
A_LOW: int
A_NORMAL: int
A_PROTECT: int
A_REVERSE: int
A_RIGHT: int
A_STANDOUT: int
A_TOP: int
A_UNDERLINE: int
A_VERTICAL: int
BUTTON1_CLICKED: int
BUTTON1_DOUBLE_CLICKED: int
BUTTON1_PRESSED: int
BUTTON1_RELEASED: int
BUTTON1_TRIPLE_CLICKED: int
BUTTON2_CLICKED: int
BUTTON2_DOUBLE_CLICKED: int
BUTTON2_PRESSED: int
BUTTON2_RELEASED: int
BUTTON2_TRIPLE_CLICKED: int
BUTTON3_CLICKED: int
BUTTON3_DOUBLE_CLICKED: int
BUTTON3_PRESSED: int
BUTTON3_RELEASED: int
BUTTON3_TRIPLE_CLICKED: int
BUTTON4_CLICKED: int
BUTTON4_DOUBLE_CLICKED: int
BUTTON4_PRESSED: int
BUTTON4_RELEASED: int
BUTTON4_TRIPLE_CLICKED: int
# Darwin ncurses doesn't provide BUTTON5_* constants prior to 3.12.10 and 3.13.3
if sys.version_info >= (3, 10):
if sys.version_info >= (3, 12) or sys.platform != "darwin":
BUTTON5_PRESSED: int
BUTTON5_RELEASED: int
BUTTON5_CLICKED: int
BUTTON5_DOUBLE_CLICKED: int
BUTTON5_TRIPLE_CLICKED: int
BUTTON_ALT: int
BUTTON_CTRL: int
BUTTON_SHIFT: int
COLOR_BLACK: int
COLOR_BLUE: int
COLOR_CYAN: int
COLOR_GREEN: int
COLOR_MAGENTA: int
COLOR_RED: int
COLOR_WHITE: int
COLOR_YELLOW: int
ERR: int
KEY_A1: int
KEY_A3: int
KEY_B2: int
KEY_BACKSPACE: int
KEY_BEG: int
KEY_BREAK: int
KEY_BTAB: int
KEY_C1: int
KEY_C3: int
KEY_CANCEL: int
KEY_CATAB: int
KEY_CLEAR: int
KEY_CLOSE: int
KEY_COMMAND: int
KEY_COPY: int
KEY_CREATE: int
KEY_CTAB: int
KEY_DC: int
KEY_DL: int
KEY_DOWN: int
KEY_EIC: int
KEY_END: int
KEY_ENTER: int
KEY_EOL: int
KEY_EOS: int
KEY_EXIT: int
KEY_F0: int
KEY_F1: int
KEY_F10: int
KEY_F11: int
KEY_F12: int
KEY_F13: int
KEY_F14: int
KEY_F15: int
KEY_F16: int
KEY_F17: int
KEY_F18: int
KEY_F19: int
KEY_F2: int
KEY_F20: int
KEY_F21: int
KEY_F22: int
KEY_F23: int
KEY_F24: int
KEY_F25: int
KEY_F26: int
KEY_F27: int
KEY_F28: int
KEY_F29: int
KEY_F3: int
KEY_F30: int
KEY_F31: int
KEY_F32: int
KEY_F33: int
KEY_F34: int
KEY_F35: int
KEY_F36: int
KEY_F37: int
KEY_F38: int
KEY_F39: int
KEY_F4: int
KEY_F40: int
KEY_F41: int
KEY_F42: int
KEY_F43: int
KEY_F44: int
KEY_F45: int
KEY_F46: int
KEY_F47: int
KEY_F48: int
KEY_F49: int
KEY_F5: int
KEY_F50: int
KEY_F51: int
KEY_F52: int
KEY_F53: int
KEY_F54: int
KEY_F55: int
KEY_F56: int
KEY_F57: int
KEY_F58: int
KEY_F59: int
KEY_F6: int
KEY_F60: int
KEY_F61: int
KEY_F62: int
KEY_F63: int
KEY_F7: int
KEY_F8: int
KEY_F9: int
KEY_FIND: int
KEY_HELP: int
KEY_HOME: int
KEY_IC: int
KEY_IL: int
KEY_LEFT: int
KEY_LL: int
KEY_MARK: int
KEY_MAX: int
KEY_MESSAGE: int
KEY_MIN: int
KEY_MOUSE: int
KEY_MOVE: int
KEY_NEXT: int
KEY_NPAGE: int
KEY_OPEN: int
KEY_OPTIONS: int
KEY_PPAGE: int
KEY_PREVIOUS: int
KEY_PRINT: int
KEY_REDO: int
KEY_REFERENCE: int
KEY_REFRESH: int
KEY_REPLACE: int
KEY_RESET: int
KEY_RESIZE: int
KEY_RESTART: int
KEY_RESUME: int
KEY_RIGHT: int
KEY_SAVE: int
KEY_SBEG: int
KEY_SCANCEL: int
KEY_SCOMMAND: int
KEY_SCOPY: int
KEY_SCREATE: int
KEY_SDC: int
KEY_SDL: int
KEY_SELECT: int
KEY_SEND: int
KEY_SEOL: int
KEY_SEXIT: int
KEY_SF: int
KEY_SFIND: int
KEY_SHELP: int
KEY_SHOME: int
KEY_SIC: int
KEY_SLEFT: int
KEY_SMESSAGE: int
KEY_SMOVE: int
KEY_SNEXT: int
KEY_SOPTIONS: int
KEY_SPREVIOUS: int
KEY_SPRINT: int
KEY_SR: int
KEY_SREDO: int
KEY_SREPLACE: int
KEY_SRESET: int
KEY_SRIGHT: int
KEY_SRSUME: int
KEY_SSAVE: int
KEY_SSUSPEND: int
KEY_STAB: int
KEY_SUNDO: int
KEY_SUSPEND: int
KEY_UNDO: int
KEY_UP: int
OK: int
REPORT_MOUSE_POSITION: int
_C_API: Any
version: 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: ...
if sys.version_info >= (3, 10):
def has_extended_color_support() -> bool: ...
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 = ..., begin_x: int = ..., /) -> 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 = ..., /) -> None: ...
def bkgdset(self, ch: _ChType, attr: int = ..., /) -> 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 = ..., horch: _ChType = ...) -> 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, yes: int) -> 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 = ..., /) -> 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, yes: 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 = ...) -> bytes: ...
@overload
def instr(self, y: int, x: int, n: int = ...) -> bytes: ...
def is_linetouched(self, line: int, /) -> bool: ...
def is_wintouched(self) -> bool: ...
def keypad(self, yes: bool, /) -> None: ...
def leaveok(self, yes: 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, yes: bool) -> None: ...
def notimeout(self, yes: 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 = ...) -> 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 = ...) -> 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

View file

@ -0,0 +1,27 @@
from _curses import window
from typing import final
__version__: str
version: 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: ...

View file

@ -0,0 +1,44 @@
import sys
from _typeshed import ReadOnlyBuffer, StrOrBytesPath
from types import TracebackType
from typing import TypeVar, final, overload, type_check_only
from typing_extensions import Self, TypeAlias
if sys.platform != "win32":
_T = TypeVar("_T")
_KeyType: TypeAlias = str | ReadOnlyBuffer
_ValueType: TypeAlias = str | ReadOnlyBuffer
class error(OSError): ...
library: 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 = ..., /) -> 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: ...

View file

@ -0,0 +1,67 @@
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
from typing_extensions import TypeAlias
_TrapType: TypeAlias = type[DecimalException]
__version__: Final[str]
__libmpdec_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]
def setcontext(context: Context, /) -> None: ...
def getcontext() -> Context: ...
if sys.version_info >= (3, 11):
def localcontext(
ctx: Context | None = None,
*,
prec: int | None = ...,
rounding: str | None = ...,
Emin: int | None = ...,
Emax: int | None = ...,
capitals: int | None = ...,
clamp: int | None = ...,
traps: dict[_TrapType, bool] | None = ...,
flags: dict[_TrapType, bool] | None = ...,
) -> _ContextManager: ...
else:
def localcontext(ctx: Context | None = None) -> _ContextManager: ...
DefaultContext: Context
BasicContext: Context
ExtendedContext: Context

View file

@ -0,0 +1,113 @@
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
# 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] = (),
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
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
def module_repr(module: types.ModuleType) -> str: ...
if sys.version_info >= (3, 10):
@staticmethod
def create_module(spec: ModuleSpec) -> types.ModuleType | None: ...
@staticmethod
def exec_module(module: types.ModuleType) -> None: ...
else:
@classmethod
def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: ...
@classmethod
def exec_module(cls, module: types.ModuleType) -> None: ...
class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):
# MetaPathFinder
if sys.version_info < (3, 12):
@classmethod
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
def module_repr(m: types.ModuleType) -> str: ...
if sys.version_info >= (3, 10):
@staticmethod
def create_module(spec: ModuleSpec) -> types.ModuleType | None: ...
else:
@classmethod
def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: ...
@staticmethod
def exec_module(module: types.ModuleType) -> None: ...

View file

@ -0,0 +1,188 @@
import _ast
import _io
import importlib.abc
import importlib.machinery
import sys
import types
from _typeshed import ReadableBuffer, StrOrBytesPath, StrPath
from _typeshed.importlib import LoaderProtocol
from collections.abc import Callable, Iterable, Iterator, Mapping, MutableSequence, Sequence
from importlib.machinery import ModuleSpec
from importlib.metadata import DistributionFinder, PathDistribution
from typing import Any, Literal
from typing_extensions import Self, deprecated
if sys.version_info >= (3, 10):
import importlib.readers
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: bytes
def cache_from_source(path: StrPath, debug_override: bool | 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 as of 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
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):
if sys.version_info >= (3, 10):
@staticmethod
def invalidate_caches() -> None: ...
else:
@classmethod
def invalidate_caches(cls) -> None: ...
if sys.version_info >= (3, 10):
@staticmethod
def find_distributions(context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ...
else:
@classmethod
def find_distributions(cls, 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
def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ...
SOURCE_SUFFIXES: list[str]
DEBUG_BYTECODE_SUFFIXES: list[str]
OPTIMIZED_BYTECODE_SUFFIXES: list[str]
BYTECODE_SUFFIXES: list[str]
EXTENSION_SUFFIXES: 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: ReadableBuffer | 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, name: str | None = None) -> str: ...
def load_module(self, name: str | None = None) -> types.ModuleType: ...
if sys.version_info >= (3, 10):
def get_resource_reader(self, name: str | None = None) -> importlib.readers.FileReader: ...
else:
def get_resource_reader(self, name: str | None = None) -> Self | None: ...
def open_resource(self, resource: str) -> _io.FileIO: ...
def resource_path(self, resource: str) -> str: ...
def is_resource(self, name: str) -> bool: ...
def contents(self) -> Iterator[str]: ...
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: ReadableBuffer | 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, name: 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("load_module() is deprecated; 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("module_repr() is deprecated, and has been removed in Python 3.12")
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("load_module() is deprecated; use exec_module() instead")
def load_module(self, fullname: str) -> types.ModuleType: ...
if sys.version_info >= (3, 10):
@staticmethod
@deprecated("module_repr() is deprecated, and has been removed in Python 3.12")
def module_repr(module: types.ModuleType) -> str: ...
def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ...
else:
@classmethod
@deprecated("module_repr() is deprecated, and has been removed in Python 3.12")
def module_repr(cls, module: types.ModuleType) -> str: ...
if sys.version_info >= (3, 13):
class AppleFrameworkLoader(ExtensionFileLoader, importlib.abc.ExecutionLoader): ...

View file

@ -0,0 +1,47 @@
import sys
from _typeshed import ReadOnlyBuffer, StrOrBytesPath
from types import TracebackType
from typing import TypeVar, overload
from typing_extensions import Self, TypeAlias
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
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: ...

View file

@ -0,0 +1,82 @@
import sys
from _typeshed import ReadableBuffer
from collections.abc import Callable
from types import ModuleType
from typing import AnyStr, Protocol, final, overload, type_check_only
from typing_extensions import Self, TypeAlias
_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: ...
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: ...
if sys.version_info >= (3, 10):
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: bytes | bytearray, msg: ReadableBuffer = b"", digestmod: _DigestMod = None) -> HMAC: ...
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: bytes | bytearray, 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: ...

View file

@ -0,0 +1,11 @@
from typing import Any, Final, TypeVar
_T = TypeVar("_T")
__about__: Final[str]
def heapify(heap: list[Any], /) -> None: ...
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: ...

View file

@ -0,0 +1,28 @@
import sys
import types
from _typeshed import ReadableBuffer
from importlib.machinery import ModuleSpec
from typing import Any
check_hash_based_pycs: str
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: ...

View file

@ -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: ...

View file

@ -0,0 +1,19 @@
from typing import Any, Literal, SupportsIndex
from typing_extensions import TypeAlias
_UnboundOp: TypeAlias = Literal[1, 2, 3]
class QueueError(RuntimeError): ...
class QueueNotFoundError(QueueError): ...
def bind(qid: SupportsIndex) -> None: ...
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]]: ...
def put(qid: SupportsIndex, obj: Any, fmt: SupportsIndex, unboundop: _UnboundOp) -> None: ...
def release(qid: SupportsIndex) -> None: ...

View file

@ -0,0 +1,52 @@
import types
from collections.abc import Callable, Mapping
from typing import Final, Literal, SupportsIndex
from typing_extensions import TypeAlias
_Configs: TypeAlias = Literal["default", "isolated", "legacy", "empty", ""]
class InterpreterError(Exception): ...
class InterpreterNotFoundError(InterpreterError): ...
class NotShareableError(ValueError): ...
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) -> list[tuple[int, int]]: ...
def get_current() -> tuple[int, int]: ...
def get_main() -> tuple[int, int]: ...
def is_running(id: SupportsIndex, *, restrict: bool = False) -> bool: ...
def get_config(id: SupportsIndex, *, restrict: bool = False) -> types.SimpleNamespace: ...
def whence(id: SupportsIndex) -> int: ...
def exec(
id: SupportsIndex, code: str | types.CodeType | Callable[[], object], shared: bool | None = None, *, restrict: bool = False
) -> None | types.SimpleNamespace: ...
def call(
id: SupportsIndex,
callable: Callable[..., object],
args: tuple[object, ...] | None = None,
kwargs: dict[str, object] | None = None,
*,
restrict: bool = False,
) -> object: ...
def run_string(
id: SupportsIndex, script: str | types.CodeType | Callable[[], object], shared: bool | None = None, *, restrict: bool = False
) -> None: ...
def run_func(
id: SupportsIndex, func: types.CodeType | Callable[[], object], shared: bool | None = None, *, restrict: bool = False
) -> None: ...
def set___main___attrs(id: SupportsIndex, updates: Mapping[str, object], *, 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: ...
def capture_exception(exc: BaseException | None = None) -> types.SimpleNamespace: ...
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

View file

@ -0,0 +1,216 @@
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
_T = TypeVar("_T")
DEFAULT_BUFFER_SIZE: Final = 8192
open = builtins.open
def open_code(path: str) -> IO[bytes]: ...
BlockingIOError = builtins.BlockingIOError
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: ...
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: ...
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: ...
class BufferedReader(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes
raw: RawIOBase
def __init__(self, raw: RawIOBase, 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: ...
class BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes
raw: RawIOBase
def __init__(self, raw: RawIOBase, 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: ...
class BufferedRandom(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes
mode: str
name: Any
raw: RawIOBase
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: ...
class BufferedRWPair(BufferedIOBase, _BufferedIOBase):
def __init__(self, reader: RawIOBase, writer: RawIOBase, 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, see the comments on TextIOWrapper.name and
# TextIO.name.
@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)
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: ...
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: ...
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: ...
if sys.version_info >= (3, 10):
@overload
def text_encoding(encoding: None, stacklevel: int = 2, /) -> Literal["locale", "utf-8"]: ...
@overload
def text_encoding(encoding: _T, stacklevel: int = 2, /) -> _T: ...

View file

@ -0,0 +1,51 @@
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) -> int | 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: int | 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:
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: ...
def scanstring(string: str, end: int, strict: bool = ...) -> tuple[str, int]: ...

View file

@ -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: ...

View file

@ -0,0 +1,35 @@
import sys
from _typeshed import structseq
from collections.abc import Callable
from types import CodeType
from typing import Any, Final, final
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]]):
if sys.version_info >= (3, 10):
__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]):
if sys.version_info >= (3, 10):
__match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime")
code: CodeType | str
callcount: int
reccallcount: int
totaltime: float
inlinetime: float

View file

@ -0,0 +1,71 @@
import sys
from _typeshed import ReadableBuffer
from collections.abc import Mapping, Sequence
from typing import Any, Final, final
from typing_extensions import Self, TypeAlias
_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: 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: int # v big number
@final
class LZMADecompressor:
if sys.version_info >= (3, 12):
def __new__(cls, format: int | None = ..., memlimit: int | None = ..., filters: _FilterChain | None = ...) -> Self: ...
else:
def __init__(self, format: int | None = ..., memlimit: int | None = ..., filters: _FilterChain | 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 | None = ..., check: int = ..., preset: int | None = ..., filters: _FilterChain | None = ...
) -> Self: ...
else:
def __init__(
self, format: int | None = ..., check: int = ..., preset: int | None = ..., filters: _FilterChain | None = ...
) -> None: ...
def compress(self, data: ReadableBuffer, /) -> bytes: ...
def flush(self) -> bytes: ...
class LZMAError(Exception): ...
def is_check_supported(check_id: int, /) -> bool: ...

View file

@ -0,0 +1,16 @@
import sys
from typing import Any
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: int = 1) -> int: ... # undocumented
def parse_declaration(self, i: int) -> int: ... # undocumented
def parse_marked_section(self, i: int, report: int = 1) -> int: ... # undocumented
def updatepos(self, i: int, j: int) -> int: ... # undocumented
if sys.version_info < (3, 10):
# Removed from ParserBase: https://bugs.python.org/issue31844
def error(self, message: str) -> Any: ... # undocumented
lineno: int # undocumented
offset: int # undocumented

View file

@ -0,0 +1,92 @@
import sys
if sys.platform == "win32":
class MSIError(Exception): ...
# Actual typename View, not exposed by the implementation
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
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
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
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[str], /) -> None: ...
def OpenDatabase(path: str, persist: int, /) -> _Database: ...
def CreateRecord(count: int, /) -> _Record: ...
MSICOLINFO_NAMES: int
MSICOLINFO_TYPES: int
MSIDBOPEN_CREATE: int
MSIDBOPEN_CREATEDIRECT: int
MSIDBOPEN_DIRECT: int
MSIDBOPEN_PATCHFILE: int
MSIDBOPEN_READONLY: int
MSIDBOPEN_TRANSACT: int
MSIMODIFY_ASSIGN: int
MSIMODIFY_DELETE: int
MSIMODIFY_INSERT: int
MSIMODIFY_INSERT_TEMPORARY: int
MSIMODIFY_MERGE: int
MSIMODIFY_REFRESH: int
MSIMODIFY_REPLACE: int
MSIMODIFY_SEEK: int
MSIMODIFY_UPDATE: int
MSIMODIFY_VALIDATE: int
MSIMODIFY_VALIDATE_DELETE: int
MSIMODIFY_VALIDATE_FIELD: int
MSIMODIFY_VALIDATE_NEW: int
PID_APPNAME: int
PID_AUTHOR: int
PID_CHARCOUNT: int
PID_CODEPAGE: int
PID_COMMENTS: int
PID_CREATE_DTM: int
PID_KEYWORDS: int
PID_LASTAUTHOR: int
PID_LASTPRINTED: int
PID_LASTSAVE_DTM: int
PID_PAGECOUNT: int
PID_REVNUMBER: int
PID_SECURITY: int
PID_SUBJECT: int
PID_TEMPLATE: int
PID_TITLE: int
PID_WORDCOUNT: int

View file

@ -0,0 +1,44 @@
from _typeshed import ReadableBuffer
from codecs import _ReadableStream, _WritableStream
from collections.abc import Iterable
from typing import final, type_check_only
# 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: ...
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: ...
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: ...
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: ...
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: ...

View file

@ -0,0 +1,115 @@
import sys
from _typeshed import SupportsGetItem
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, Protocol, SupportsAbs, SupportsIndex, TypeVar, overload
from typing_extensions import ParamSpec, TypeAlias, TypeIs
_R = TypeVar("_R")
_T = TypeVar("_T")
_T_co = TypeVar("_T_co", covariant=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.
class _SupportsDunderLT(Protocol):
def __lt__(self, other: Any, /) -> Any: ...
class _SupportsDunderGT(Protocol):
def __gt__(self, other: Any, /) -> Any: ...
class _SupportsDunderLE(Protocol):
def __le__(self, other: Any, /) -> Any: ...
class _SupportsDunderGE(Protocol):
def __ge__(self, other: Any, /) -> Any: ...
_SupportsComparison: TypeAlias = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT
class _SupportsInversion(Protocol[_T_co]):
def __invert__(self) -> _T_co: ...
class _SupportsNeg(Protocol[_T_co]):
def __neg__(self) -> _T_co: ...
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: ...
def add(a: Any, b: Any, /) -> Any: ...
def and_(a: Any, b: Any, /) -> Any: ...
def floordiv(a: Any, b: Any, /) -> Any: ...
def index(a: SupportsIndex, /) -> int: ...
def inv(a: _SupportsInversion[_T_co], /) -> _T_co: ...
def invert(a: _SupportsInversion[_T_co], /) -> _T_co: ...
def lshift(a: Any, b: Any, /) -> Any: ...
def mod(a: Any, b: Any, /) -> Any: ...
def mul(a: Any, b: Any, /) -> Any: ...
def matmul(a: Any, b: Any, /) -> Any: ...
def neg(a: _SupportsNeg[_T_co], /) -> _T_co: ...
def or_(a: Any, b: Any, /) -> Any: ...
def pos(a: _SupportsPos[_T_co], /) -> _T_co: ...
def pow(a: Any, b: Any, /) -> Any: ...
def rshift(a: Any, b: Any, /) -> Any: ...
def sub(a: Any, b: Any, /) -> Any: ...
def truediv(a: Any, b: Any, /) -> Any: ...
def xor(a: Any, b: Any, /) -> Any: ...
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: SupportsIndex, /) -> None: ...
@overload
def delitem(a: MutableSequence[Any], b: slice, /) -> None: ...
@overload
def delitem(a: MutableMapping[_K, Any], b: _K, /) -> None: ...
@overload
def getitem(a: Sequence[_T], b: slice, /) -> 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: SupportsIndex, c: _T, /) -> None: ...
@overload
def setitem(a: MutableSequence[_T], b: slice, 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: Any, b: Any, /) -> Any: ...
def iand(a: Any, b: Any, /) -> Any: ...
def iconcat(a: Any, b: Any, /) -> Any: ...
def ifloordiv(a: Any, b: Any, /) -> Any: ...
def ilshift(a: Any, b: Any, /) -> Any: ...
def imod(a: Any, b: Any, /) -> Any: ...
def imul(a: Any, b: Any, /) -> Any: ...
def imatmul(a: Any, b: Any, /) -> Any: ...
def ior(a: Any, b: Any, /) -> Any: ...
def ipow(a: Any, b: Any, /) -> Any: ...
def irshift(a: Any, b: Any, /) -> Any: ...
def isub(a: Any, b: Any, /) -> Any: ...
def itruediv(a: Any, b: Any, /) -> Any: ...
def ixor(a: Any, b: Any, /) -> Any: ...
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]: ...

View file

@ -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]: ...

View file

@ -0,0 +1,104 @@
from _typeshed import ReadableBuffer, SupportsWrite
from collections.abc import Callable, Iterable, Iterator, Mapping
from pickle import PickleBuffer as PickleBuffer
from typing import Any, Protocol, type_check_only
from typing_extensions import TypeAlias
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]]: ...
class Pickler:
fast: bool
dispatch_table: Mapping[type, Callable[[Any], _ReducedType]]
reducer_override: Callable[[Any], Any]
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: ...
@type_check_only
class UnpicklerMemoProxy:
def clear(self, /) -> None: ...
def copy(self, /) -> dict[int, tuple[int, Any]]: ...
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: ...

View file

@ -0,0 +1,32 @@
import sys
from _typeshed import StrOrBytesPath
from collections.abc import Callable, Sequence
from typing import SupportsIndex
if sys.platform != "win32":
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],
allow_vfork: bool,
/,
) -> int: ...

View file

@ -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]: ...

View file

@ -0,0 +1,43 @@
# This is a slight lie, the implementations aren't exactly identical
# However, in all likelihood, the differences are inconsequential
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",
]

View file

@ -0,0 +1,16 @@
from types import GenericAlias
from typing import Any, Generic, TypeVar
_T = TypeVar("_T")
class Empty(Exception): ...
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: ...

View file

@ -0,0 +1,12 @@
from typing_extensions import TypeAlias
# Actually Tuple[(int,) * 625]
_State: TypeAlias = tuple[int, ...]
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: ...

View file

@ -0,0 +1,17 @@
import sys
from collections.abc import Iterable
from typing import ClassVar, Literal, NoReturn
class Quitter:
name: str
eof: str
def __init__(self, name: str, eof: str) -> None: ...
def __call__(self, code: sys._ExitCode = None) -> NoReturn: ...
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: ...

View file

@ -0,0 +1,834 @@
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, SupportsIndex, overload
from typing_extensions import CapsuleType, TypeAlias
_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.
_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: int
AF_INET: int
AF_INET6: int
AF_UNSPEC: int
SOCK_STREAM: int
SOCK_DGRAM: int
SOCK_RAW: int
SOCK_RDM: int
SOCK_SEQPACKET: int
if sys.platform == "linux":
# Availability: Linux >= 2.6.27
SOCK_CLOEXEC: int
SOCK_NONBLOCK: 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: int
SO_BROADCAST: int
SO_DEBUG: int
SO_DONTROUTE: int
SO_ERROR: int
SO_KEEPALIVE: int
SO_LINGER: int
SO_OOBINLINE: int
SO_RCVBUF: int
SO_RCVLOWAT: int
SO_RCVTIMEO: int
SO_REUSEADDR: int
SO_SNDBUF: int
SO_SNDLOWAT: int
SO_SNDTIMEO: int
SO_TYPE: int
if sys.platform != "linux":
SO_USELOOPBACK: int
if sys.platform == "win32":
SO_EXCLUSIVEADDRUSE: int
if sys.platform != "win32":
SO_REUSEPORT: int
if sys.platform != "darwin" or sys.version_info >= (3, 13):
SO_BINDTODEVICE: int
if sys.platform != "win32" and sys.platform != "darwin":
SO_DOMAIN: int
SO_MARK: int
SO_PASSCRED: int
SO_PASSSEC: int
SO_PEERCRED: int
SO_PEERSEC: int
SO_PRIORITY: int
SO_PROTOCOL: int
if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux":
SO_SETFIB: int
if sys.platform == "linux" and sys.version_info >= (3, 13):
SO_BINDTOIFINDEX: int
SOMAXCONN: int
MSG_CTRUNC: int
MSG_DONTROUTE: int
MSG_OOB: int
MSG_PEEK: int
MSG_TRUNC: int
MSG_WAITALL: int
if sys.platform != "win32":
MSG_DONTWAIT: int
MSG_EOR: int
MSG_NOSIGNAL: int # Sometimes this exists on darwin, sometimes not
if sys.platform != "darwin":
MSG_ERRQUEUE: int
if sys.platform == "win32":
MSG_BCAST: int
MSG_MCAST: int
if sys.platform != "win32" and sys.platform != "darwin":
MSG_CMSG_CLOEXEC: int
MSG_CONFIRM: int
MSG_FASTOPEN: int
MSG_MORE: int
if sys.platform != "win32" and sys.platform != "linux":
MSG_EOF: int
if sys.platform != "win32" and sys.platform != "linux" and sys.platform != "darwin":
MSG_NOTIFICATION: int
MSG_BTAG: int # Not FreeBSD either
MSG_ETAG: int # Not FreeBSD either
SOL_IP: int
SOL_SOCKET: int
SOL_TCP: int
SOL_UDP: 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: int
SOL_AX25: int
SOL_HCI: int
SOL_IPX: int
SOL_NETROM: int
SOL_ROSE: int
if sys.platform != "win32":
SCM_RIGHTS: int
if sys.platform != "win32" and sys.platform != "darwin":
SCM_CREDENTIALS: int
if sys.platform != "win32" and sys.platform != "linux":
SCM_CREDS: int
IPPROTO_ICMP: int
IPPROTO_IP: int
IPPROTO_RAW: int
IPPROTO_TCP: int
IPPROTO_UDP: int
IPPROTO_AH: int
IPPROTO_DSTOPTS: int
IPPROTO_EGP: int
IPPROTO_ESP: int
IPPROTO_FRAGMENT: int
IPPROTO_HOPOPTS: int
IPPROTO_ICMPV6: int
IPPROTO_IDP: int
IPPROTO_IGMP: int
IPPROTO_IPV6: int
IPPROTO_NONE: int
IPPROTO_PIM: int
IPPROTO_PUP: int
IPPROTO_ROUTING: int
IPPROTO_SCTP: int
if sys.platform != "linux":
IPPROTO_GGP: int
IPPROTO_IPV4: int
IPPROTO_MAX: int
IPPROTO_ND: int
if sys.platform == "win32":
IPPROTO_CBT: int
IPPROTO_ICLFXBM: int
IPPROTO_IGP: int
IPPROTO_L2TP: int
IPPROTO_PGM: int
IPPROTO_RDP: int
IPPROTO_ST: int
if sys.platform != "win32":
IPPROTO_GRE: int
IPPROTO_IPIP: int
IPPROTO_RSVP: int
IPPROTO_TP: int
if sys.platform != "win32" and sys.platform != "linux":
IPPROTO_EON: int
IPPROTO_HELLO: int
IPPROTO_IPCOMP: int
IPPROTO_XTP: int
if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux":
IPPROTO_BIP: int # Not FreeBSD either
IPPROTO_MOBILE: int # Not FreeBSD either
IPPROTO_VRRP: int # Not FreeBSD either
if sys.platform == "linux":
# Availability: Linux >= 2.6.20, FreeBSD >= 10.1
IPPROTO_UDPLITE: int
if sys.version_info >= (3, 10) and sys.platform == "linux":
IPPROTO_MPTCP: int
IPPORT_RESERVED: int
IPPORT_USERRESERVED: int
INADDR_ALLHOSTS_GROUP: int
INADDR_ANY: int
INADDR_BROADCAST: int
INADDR_LOOPBACK: int
INADDR_MAX_LOCAL_GROUP: int
INADDR_NONE: int
INADDR_UNSPEC_GROUP: int
IP_ADD_MEMBERSHIP: int
IP_DROP_MEMBERSHIP: int
IP_HDRINCL: int
IP_MULTICAST_IF: int
IP_MULTICAST_LOOP: int
IP_MULTICAST_TTL: int
IP_OPTIONS: int
if sys.platform != "linux":
IP_RECVDSTADDR: int
if sys.version_info >= (3, 10):
IP_RECVTOS: int
IP_TOS: int
IP_TTL: int
if sys.platform != "win32":
IP_DEFAULT_MULTICAST_LOOP: int
IP_DEFAULT_MULTICAST_TTL: int
IP_MAX_MEMBERSHIPS: int
IP_RECVOPTS: int
IP_RECVRETOPTS: int
IP_RETOPTS: int
if sys.platform != "win32" and sys.platform != "darwin":
IP_TRANSPARENT: int
if sys.platform != "win32" and sys.platform != "darwin" and sys.version_info >= (3, 11):
IP_BIND_ADDRESS_NO_PORT: int
if sys.version_info >= (3, 12):
IP_ADD_SOURCE_MEMBERSHIP: int
IP_BLOCK_SOURCE: int
IP_DROP_SOURCE_MEMBERSHIP: int
IP_PKTINFO: int
IP_UNBLOCK_SOURCE: int
IPV6_CHECKSUM: int
IPV6_JOIN_GROUP: int
IPV6_LEAVE_GROUP: int
IPV6_MULTICAST_HOPS: int
IPV6_MULTICAST_IF: int
IPV6_MULTICAST_LOOP: int
IPV6_RECVTCLASS: int
IPV6_TCLASS: int
IPV6_UNICAST_HOPS: int
IPV6_V6ONLY: int
IPV6_DONTFRAG: int
IPV6_HOPLIMIT: int
IPV6_HOPOPTS: int
IPV6_PKTINFO: int
IPV6_RECVRTHDR: int
IPV6_RTHDR: int
if sys.platform != "win32":
IPV6_RTHDR_TYPE_0: int
IPV6_DSTOPTS: int
IPV6_NEXTHOP: int
IPV6_PATHMTU: int
IPV6_RECVDSTOPTS: int
IPV6_RECVHOPLIMIT: int
IPV6_RECVHOPOPTS: int
IPV6_RECVPATHMTU: int
IPV6_RECVPKTINFO: int
IPV6_RTHDRDSTOPTS: int
if sys.platform != "win32" and sys.platform != "linux":
IPV6_USE_MIN_MTU: int
EAI_AGAIN: int
EAI_BADFLAGS: int
EAI_FAIL: int
EAI_FAMILY: int
EAI_MEMORY: int
EAI_NODATA: int
EAI_NONAME: int
EAI_SERVICE: int
EAI_SOCKTYPE: int
if sys.platform != "win32":
EAI_ADDRFAMILY: int
EAI_OVERFLOW: int
EAI_SYSTEM: int
if sys.platform != "win32" and sys.platform != "linux":
EAI_BADHINTS: int
EAI_MAX: int
EAI_PROTOCOL: int
AI_ADDRCONFIG: int
AI_ALL: int
AI_CANONNAME: int
AI_NUMERICHOST: int
AI_NUMERICSERV: int
AI_PASSIVE: int
AI_V4MAPPED: int
if sys.platform != "win32" and sys.platform != "linux":
AI_DEFAULT: int
AI_MASK: int
AI_V4MAPPED_CFG: int
NI_DGRAM: int
NI_MAXHOST: int
NI_MAXSERV: int
NI_NAMEREQD: int
NI_NOFQDN: int
NI_NUMERICHOST: int
NI_NUMERICSERV: int
if sys.platform == "linux" and sys.version_info >= (3, 13):
NI_IDN: int
TCP_FASTOPEN: int
TCP_KEEPCNT: int
TCP_KEEPINTVL: int
TCP_MAXSEG: int
TCP_NODELAY: int
if sys.platform != "win32":
TCP_NOTSENT_LOWAT: int
if sys.platform != "darwin":
TCP_KEEPIDLE: int
if sys.version_info >= (3, 10) and sys.platform == "darwin":
TCP_KEEPALIVE: int
if sys.version_info >= (3, 11) and sys.platform == "darwin":
TCP_CONNECTION_INFO: int
if sys.platform != "win32" and sys.platform != "darwin":
TCP_CONGESTION: int
TCP_CORK: int
TCP_DEFER_ACCEPT: int
TCP_INFO: int
TCP_LINGER2: int
TCP_QUICKACK: int
TCP_SYNCNT: int
TCP_USER_TIMEOUT: int
TCP_WINDOW_CLAMP: int
if sys.platform == "linux" and sys.version_info >= (3, 12):
TCP_CC_INFO: int
TCP_FASTOPEN_CONNECT: int
TCP_FASTOPEN_KEY: int
TCP_FASTOPEN_NO_COOKIE: int
TCP_INQ: int
TCP_MD5SIG: int
TCP_MD5SIG_EXT: int
TCP_QUEUE_SEQ: int
TCP_REPAIR: int
TCP_REPAIR_OPTIONS: int
TCP_REPAIR_QUEUE: int
TCP_REPAIR_WINDOW: int
TCP_SAVED_SYN: int
TCP_SAVE_SYN: int
TCP_THIN_DUPACK: int
TCP_THIN_LINEAR_TIMEOUTS: int
TCP_TIMESTAMP: int
TCP_TX_DELAY: int
TCP_ULP: int
TCP_ZEROCOPY_RECEIVE: int
# --------------------
# Specifically documented constants
# --------------------
if sys.platform == "linux":
# Availability: Linux >= 2.6.25, NetBSD >= 8
AF_CAN: int
PF_CAN: int
SOL_CAN_BASE: int
SOL_CAN_RAW: int
CAN_EFF_FLAG: int
CAN_EFF_MASK: int
CAN_ERR_FLAG: int
CAN_ERR_MASK: int
CAN_RAW: int
CAN_RAW_FILTER: int
CAN_RAW_LOOPBACK: int
CAN_RAW_RECV_OWN_MSGS: int
CAN_RTR_FLAG: int
CAN_SFF_MASK: int
if sys.version_info < (3, 11):
CAN_RAW_ERR_FILTER: int
if sys.platform == "linux":
# Availability: Linux >= 2.6.25
CAN_BCM: int
CAN_BCM_TX_SETUP: int
CAN_BCM_TX_DELETE: int
CAN_BCM_TX_READ: int
CAN_BCM_TX_SEND: int
CAN_BCM_RX_SETUP: int
CAN_BCM_RX_DELETE: int
CAN_BCM_RX_READ: int
CAN_BCM_TX_STATUS: int
CAN_BCM_TX_EXPIRED: int
CAN_BCM_RX_STATUS: int
CAN_BCM_RX_TIMEOUT: int
CAN_BCM_RX_CHANGED: int
CAN_BCM_SETTIMER: int
CAN_BCM_STARTTIMER: int
CAN_BCM_TX_COUNTEVT: int
CAN_BCM_TX_ANNOUNCE: int
CAN_BCM_TX_CP_CAN_ID: int
CAN_BCM_RX_FILTER_ID: int
CAN_BCM_RX_CHECK_DLC: int
CAN_BCM_RX_NO_AUTOTIMER: int
CAN_BCM_RX_ANNOUNCE_RESUME: int
CAN_BCM_TX_RESET_MULTI_IDX: int
CAN_BCM_RX_RTR_FRAME: int
CAN_BCM_CAN_FD_FRAME: int
if sys.platform == "linux":
# Availability: Linux >= 3.6
CAN_RAW_FD_FRAMES: int
# Availability: Linux >= 4.1
CAN_RAW_JOIN_FILTERS: int
# Availability: Linux >= 2.6.25
CAN_ISOTP: int
# Availability: Linux >= 5.4
CAN_J1939: int
J1939_MAX_UNICAST_ADDR: int
J1939_IDLE_ADDR: int
J1939_NO_ADDR: int
J1939_NO_NAME: int
J1939_PGN_REQUEST: int
J1939_PGN_ADDRESS_CLAIMED: int
J1939_PGN_ADDRESS_COMMANDED: int
J1939_PGN_PDU1_MAX: int
J1939_PGN_MAX: int
J1939_NO_PGN: int
SO_J1939_FILTER: int
SO_J1939_PROMISC: int
SO_J1939_SEND_PRIO: int
SO_J1939_ERRQUEUE: int
SCM_J1939_DEST_ADDR: int
SCM_J1939_DEST_NAME: int
SCM_J1939_PRIO: int
SCM_J1939_ERRQUEUE: int
J1939_NLA_PAD: int
J1939_NLA_BYTES_ACKED: int
J1939_EE_INFO_NONE: int
J1939_EE_INFO_TX_ABORT: int
J1939_FILTER_MAX: 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: int
PF_DIVERT: int
if sys.platform == "linux":
# Availability: Linux >= 2.2
AF_PACKET: int
PF_PACKET: int
PACKET_BROADCAST: int
PACKET_FASTROUTE: int
PACKET_HOST: int
PACKET_LOOPBACK: int
PACKET_MULTICAST: int
PACKET_OTHERHOST: int
PACKET_OUTGOING: int
if sys.version_info >= (3, 12) and sys.platform == "linux":
ETH_P_ALL: int
if sys.platform == "linux":
# Availability: Linux >= 2.6.30
AF_RDS: int
PF_RDS: int
SOL_RDS: int
# These are present in include/linux/rds.h but don't always show up
# here.
RDS_CANCEL_SENT_TO: int
RDS_CMSG_RDMA_ARGS: int
RDS_CMSG_RDMA_DEST: int
RDS_CMSG_RDMA_MAP: int
RDS_CMSG_RDMA_STATUS: int
RDS_CONG_MONITOR: int
RDS_FREE_MR: int
RDS_GET_MR: int
RDS_GET_MR_FOR_DEST: int
RDS_RDMA_DONTWAIT: int
RDS_RDMA_FENCE: int
RDS_RDMA_INVALIDATE: int
RDS_RDMA_NOTIFY_ME: int
RDS_RDMA_READWRITE: int
RDS_RDMA_SILENT: int
RDS_RDMA_USE_ONCE: int
RDS_RECVERR: 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: int
if sys.platform == "win32":
SIO_RCVALL: int
SIO_KEEPALIVE_VALS: int
SIO_LOOPBACK_FAST_PATH: int
RCVALL_MAX: int
RCVALL_OFF: int
RCVALL_ON: int
RCVALL_SOCKETLEVELONLY: int
if sys.platform == "linux":
AF_TIPC: int
SOL_TIPC: int
TIPC_ADDR_ID: int
TIPC_ADDR_NAME: int
TIPC_ADDR_NAMESEQ: int
TIPC_CFG_SRV: int
TIPC_CLUSTER_SCOPE: int
TIPC_CONN_TIMEOUT: int
TIPC_CRITICAL_IMPORTANCE: int
TIPC_DEST_DROPPABLE: int
TIPC_HIGH_IMPORTANCE: int
TIPC_IMPORTANCE: int
TIPC_LOW_IMPORTANCE: int
TIPC_MEDIUM_IMPORTANCE: int
TIPC_NODE_SCOPE: int
TIPC_PUBLISHED: int
TIPC_SRC_DROPPABLE: int
TIPC_SUBSCR_TIMEOUT: int
TIPC_SUB_CANCEL: int
TIPC_SUB_PORTS: int
TIPC_SUB_SERVICE: int
TIPC_TOP_SRV: int
TIPC_WAIT_FOREVER: int
TIPC_WITHDRAWN: int
TIPC_ZONE_SCOPE: int
if sys.platform == "linux":
# Availability: Linux >= 2.6.38
AF_ALG: int
SOL_ALG: int
ALG_OP_DECRYPT: int
ALG_OP_ENCRYPT: int
ALG_OP_SIGN: int
ALG_OP_VERIFY: int
ALG_SET_AEAD_ASSOCLEN: int
ALG_SET_AEAD_AUTHSIZE: int
ALG_SET_IV: int
ALG_SET_KEY: int
ALG_SET_OP: int
ALG_SET_PUBKEY: int
if sys.platform == "linux":
# Availability: Linux >= 4.8 (or maybe 3.9, CPython docs are confusing)
AF_VSOCK: int
IOCTL_VM_SOCKETS_GET_LOCAL_CID: int
VMADDR_CID_ANY: int
VMADDR_CID_HOST: int
VMADDR_PORT_ANY: int
SO_VM_SOCKETS_BUFFER_MAX_SIZE: int
SO_VM_SOCKETS_BUFFER_SIZE: int
SO_VM_SOCKETS_BUFFER_MIN_SIZE: int
VM_SOCKETS_INVALID_VERSION: int # undocumented
# Documented as only available on BSD, macOS, but empirically sometimes
# available on Windows
if sys.platform != "linux":
AF_LINK: int
has_ipv6: bool
if sys.platform != "darwin" and sys.platform != "linux":
BDADDR_ANY: str
BDADDR_LOCAL: str
if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux":
HCI_FILTER: int # not in NetBSD or DragonFlyBSD
HCI_TIME_STAMP: int # not in FreeBSD, NetBSD, or DragonFlyBSD
HCI_DATA_DIR: int # not in FreeBSD, NetBSD, or DragonFlyBSD
if sys.platform == "linux":
AF_QIPCRTR: 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: int
LOCAL_CREDS: int
LOCAL_CREDS_PERSISTENT: int
if sys.version_info >= (3, 11) and sys.platform == "linux":
SO_INCOMING_CPU: int # Availability: Linux >= 3.9
if sys.version_info >= (3, 12) and sys.platform == "win32":
# Availability: Windows
AF_HYPERV: int
HV_PROTOCOL_RAW: int
HVSOCKET_CONNECT_TIMEOUT: int
HVSOCKET_CONNECT_TIMEOUT_MAX: int
HVSOCKET_CONNECTED_SUSPEND: int
HVSOCKET_ADDRESS_FLAG_PASSTHRU: int
HV_GUID_ZERO: str
HV_GUID_WILDCARD: str
HV_GUID_BROADCAST: str
HV_GUID_CHILDREN: str
HV_GUID_LOOPBACK: str
HV_GUID_PARENT: str
if sys.version_info >= (3, 12):
if sys.platform != "win32":
# Availability: Linux, FreeBSD, macOS
ETHERTYPE_ARP: int
ETHERTYPE_IP: int
ETHERTYPE_IPV6: int
ETHERTYPE_VLAN: 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: int
NETLINK_CRYPTO: int
NETLINK_DNRTMSG: int
NETLINK_FIREWALL: int
NETLINK_IP6_FW: int
NETLINK_NFLOG: int
NETLINK_ROUTE: int
NETLINK_USERSOCK: int
NETLINK_XFRM: int
# Technically still supported by CPython
# NETLINK_ARPD: int # linux 2.0 to 2.6.12 (EOL August 2005)
# NETLINK_ROUTE6: int # linux 2.2 to 2.6.12 (EOL August 2005)
# NETLINK_SKIP: int # linux 2.0 to 2.6.12 (EOL August 2005)
# NETLINK_TAPBASE: int # linux 2.2 to 2.6.12 (EOL August 2005)
# NETLINK_TCPDIAG: int # linux 2.6.0 to 2.6.13 (EOL December 2005)
# NETLINK_W1: int # linux 2.6.13 to 2.6.17 (EOL October 2006)
if sys.platform == "darwin":
PF_SYSTEM: int
SYSPROTO_CONTROL: int
if sys.platform != "darwin" and sys.platform != "linux":
AF_BLUETOOTH: int
if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux":
# Linux and some BSD support is explicit in the docs
# Windows and macOS do not support in practice
BTPROTO_HCI: int
BTPROTO_L2CAP: int
BTPROTO_SCO: int # not in FreeBSD
if sys.platform != "darwin" and sys.platform != "linux":
BTPROTO_RFCOMM: int
if sys.platform == "linux":
UDPLITE_RECV_CSCOV: int
UDPLITE_SEND_CSCOV: int
# --------------------
# Documented under socket.shutdown
# --------------------
SHUT_RD: int
SHUT_RDWR: int
SHUT_WR: int
# --------------------
# Undocumented constants
# --------------------
# Undocumented address families
AF_APPLETALK: int
AF_DECnet: int
AF_IPX: int
AF_SNA: int
if sys.platform != "win32":
AF_ROUTE: int
if sys.platform == "darwin":
AF_SYSTEM: int
if sys.platform != "darwin":
AF_IRDA: int
if sys.platform != "win32" and sys.platform != "darwin":
AF_ASH: int
AF_ATMPVC: int
AF_ATMSVC: int
AF_AX25: int
AF_BRIDGE: int
AF_ECONET: int
AF_KEY: int
AF_LLC: int
AF_NETBEUI: int
AF_NETROM: int
AF_PPPOX: int
AF_ROSE: int
AF_SECURITY: int
AF_WANPIPE: int
AF_X25: int
# Miscellaneous undocumented
if sys.platform != "win32" and sys.platform != "linux":
LOCAL_PEERCRED: 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: int
# ===== Classes =====
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: ... # noqa: F811
if sys.platform == "win32":
def __init__(
self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | bytes | None = ...
) -> None: ...
else:
def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | 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 = ..., /) -> bytes: ...
def recvfrom(self, bufsize: int, flags: int = ..., /) -> tuple[bytes, _RetAddress]: ...
if sys.platform != "win32":
def recvmsg(self, bufsize: int, ancbufsize: int = ..., flags: int = ..., /) -> tuple[bytes, list[_CMSG], int, Any]: ...
def recvmsg_into(
self, buffers: Iterable[WriteableBuffer], ancbufsize: int = ..., flags: int = ..., /
) -> tuple[int, list[_CMSG], int, Any]: ...
def recvfrom_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ...
def recv_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> int: ...
def send(self, data: ReadableBuffer, flags: int = ..., /) -> int: ...
def sendall(self, data: ReadableBuffer, flags: int = ..., /) -> 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 = ...,
address: _Address | None = ...,
/,
) -> int: ...
if sys.platform == "linux":
def sendmsg_afalg(
self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ...
) -> 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 = ...,
proto: int = ...,
flags: int = ...,
) -> 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: ... # noqa: F811
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 = ..., /) -> tuple[socket, socket]: ...
def if_nameindex() -> list[tuple[int, str]]: ...
def if_nametoindex(oname: str, /) -> int: ...
def if_indextoname(index: int, /) -> str: ...
CAPI: CapsuleType

View file

@ -0,0 +1,312 @@
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,
)
from typing import Any, Final, Literal, TypeVar, overload
from typing_extensions import TypeAlias
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[int]
PARSE_DECLTYPES: Final[int]
SQLITE_ALTER_TABLE: Final[int]
SQLITE_ANALYZE: Final[int]
SQLITE_ATTACH: Final[int]
SQLITE_CREATE_INDEX: Final[int]
SQLITE_CREATE_TABLE: Final[int]
SQLITE_CREATE_TEMP_INDEX: Final[int]
SQLITE_CREATE_TEMP_TABLE: Final[int]
SQLITE_CREATE_TEMP_TRIGGER: Final[int]
SQLITE_CREATE_TEMP_VIEW: Final[int]
SQLITE_CREATE_TRIGGER: Final[int]
SQLITE_CREATE_VIEW: Final[int]
SQLITE_CREATE_VTABLE: Final[int]
SQLITE_DELETE: Final[int]
SQLITE_DENY: Final[int]
SQLITE_DETACH: Final[int]
SQLITE_DONE: Final[int]
SQLITE_DROP_INDEX: Final[int]
SQLITE_DROP_TABLE: Final[int]
SQLITE_DROP_TEMP_INDEX: Final[int]
SQLITE_DROP_TEMP_TABLE: Final[int]
SQLITE_DROP_TEMP_TRIGGER: Final[int]
SQLITE_DROP_TEMP_VIEW: Final[int]
SQLITE_DROP_TRIGGER: Final[int]
SQLITE_DROP_VIEW: Final[int]
SQLITE_DROP_VTABLE: Final[int]
SQLITE_FUNCTION: Final[int]
SQLITE_IGNORE: Final[int]
SQLITE_INSERT: Final[int]
SQLITE_OK: Final[int]
SQLITE_PRAGMA: Final[int]
SQLITE_READ: Final[int]
SQLITE_RECURSIVE: Final[int]
SQLITE_REINDEX: Final[int]
SQLITE_SAVEPOINT: Final[int]
SQLITE_SELECT: Final[int]
SQLITE_TRANSACTION: Final[int]
SQLITE_UPDATE: Final[int]
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[int]
SQLITE_DBCONFIG_DEFENSIVE: Final[int]
SQLITE_DBCONFIG_DQS_DDL: Final[int]
SQLITE_DBCONFIG_DQS_DML: Final[int]
SQLITE_DBCONFIG_ENABLE_FKEY: Final[int]
SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER: Final[int]
SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION: Final[int]
SQLITE_DBCONFIG_ENABLE_QPSG: Final[int]
SQLITE_DBCONFIG_ENABLE_TRIGGER: Final[int]
SQLITE_DBCONFIG_ENABLE_VIEW: Final[int]
SQLITE_DBCONFIG_LEGACY_ALTER_TABLE: Final[int]
SQLITE_DBCONFIG_LEGACY_FILE_FORMAT: Final[int]
SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: Final[int]
SQLITE_DBCONFIG_RESET_DATABASE: Final[int]
SQLITE_DBCONFIG_TRIGGER_EQP: Final[int]
SQLITE_DBCONFIG_TRUSTED_SCHEMA: Final[int]
SQLITE_DBCONFIG_WRITABLE_SCHEMA: Final[int]
if sys.version_info >= (3, 11):
SQLITE_ABORT: Final[int]
SQLITE_ABORT_ROLLBACK: Final[int]
SQLITE_AUTH: Final[int]
SQLITE_AUTH_USER: Final[int]
SQLITE_BUSY: Final[int]
SQLITE_BUSY_RECOVERY: Final[int]
SQLITE_BUSY_SNAPSHOT: Final[int]
SQLITE_BUSY_TIMEOUT: Final[int]
SQLITE_CANTOPEN: Final[int]
SQLITE_CANTOPEN_CONVPATH: Final[int]
SQLITE_CANTOPEN_DIRTYWAL: Final[int]
SQLITE_CANTOPEN_FULLPATH: Final[int]
SQLITE_CANTOPEN_ISDIR: Final[int]
SQLITE_CANTOPEN_NOTEMPDIR: Final[int]
SQLITE_CANTOPEN_SYMLINK: Final[int]
SQLITE_CONSTRAINT: Final[int]
SQLITE_CONSTRAINT_CHECK: Final[int]
SQLITE_CONSTRAINT_COMMITHOOK: Final[int]
SQLITE_CONSTRAINT_FOREIGNKEY: Final[int]
SQLITE_CONSTRAINT_FUNCTION: Final[int]
SQLITE_CONSTRAINT_NOTNULL: Final[int]
SQLITE_CONSTRAINT_PINNED: Final[int]
SQLITE_CONSTRAINT_PRIMARYKEY: Final[int]
SQLITE_CONSTRAINT_ROWID: Final[int]
SQLITE_CONSTRAINT_TRIGGER: Final[int]
SQLITE_CONSTRAINT_UNIQUE: Final[int]
SQLITE_CONSTRAINT_VTAB: Final[int]
SQLITE_CORRUPT: Final[int]
SQLITE_CORRUPT_INDEX: Final[int]
SQLITE_CORRUPT_SEQUENCE: Final[int]
SQLITE_CORRUPT_VTAB: Final[int]
SQLITE_EMPTY: Final[int]
SQLITE_ERROR: Final[int]
SQLITE_ERROR_MISSING_COLLSEQ: Final[int]
SQLITE_ERROR_RETRY: Final[int]
SQLITE_ERROR_SNAPSHOT: Final[int]
SQLITE_FORMAT: Final[int]
SQLITE_FULL: Final[int]
SQLITE_INTERNAL: Final[int]
SQLITE_INTERRUPT: Final[int]
SQLITE_IOERR: Final[int]
SQLITE_IOERR_ACCESS: Final[int]
SQLITE_IOERR_AUTH: Final[int]
SQLITE_IOERR_BEGIN_ATOMIC: Final[int]
SQLITE_IOERR_BLOCKED: Final[int]
SQLITE_IOERR_CHECKRESERVEDLOCK: Final[int]
SQLITE_IOERR_CLOSE: Final[int]
SQLITE_IOERR_COMMIT_ATOMIC: Final[int]
SQLITE_IOERR_CONVPATH: Final[int]
SQLITE_IOERR_CORRUPTFS: Final[int]
SQLITE_IOERR_DATA: Final[int]
SQLITE_IOERR_DELETE: Final[int]
SQLITE_IOERR_DELETE_NOENT: Final[int]
SQLITE_IOERR_DIR_CLOSE: Final[int]
SQLITE_IOERR_DIR_FSYNC: Final[int]
SQLITE_IOERR_FSTAT: Final[int]
SQLITE_IOERR_FSYNC: Final[int]
SQLITE_IOERR_GETTEMPPATH: Final[int]
SQLITE_IOERR_LOCK: Final[int]
SQLITE_IOERR_MMAP: Final[int]
SQLITE_IOERR_NOMEM: Final[int]
SQLITE_IOERR_RDLOCK: Final[int]
SQLITE_IOERR_READ: Final[int]
SQLITE_IOERR_ROLLBACK_ATOMIC: Final[int]
SQLITE_IOERR_SEEK: Final[int]
SQLITE_IOERR_SHMLOCK: Final[int]
SQLITE_IOERR_SHMMAP: Final[int]
SQLITE_IOERR_SHMOPEN: Final[int]
SQLITE_IOERR_SHMSIZE: Final[int]
SQLITE_IOERR_SHORT_READ: Final[int]
SQLITE_IOERR_TRUNCATE: Final[int]
SQLITE_IOERR_UNLOCK: Final[int]
SQLITE_IOERR_VNODE: Final[int]
SQLITE_IOERR_WRITE: Final[int]
SQLITE_LIMIT_ATTACHED: Final[int]
SQLITE_LIMIT_COLUMN: Final[int]
SQLITE_LIMIT_COMPOUND_SELECT: Final[int]
SQLITE_LIMIT_EXPR_DEPTH: Final[int]
SQLITE_LIMIT_FUNCTION_ARG: Final[int]
SQLITE_LIMIT_LENGTH: Final[int]
SQLITE_LIMIT_LIKE_PATTERN_LENGTH: Final[int]
SQLITE_LIMIT_SQL_LENGTH: Final[int]
SQLITE_LIMIT_TRIGGER_DEPTH: Final[int]
SQLITE_LIMIT_VARIABLE_NUMBER: Final[int]
SQLITE_LIMIT_VDBE_OP: Final[int]
SQLITE_LIMIT_WORKER_THREADS: Final[int]
SQLITE_LOCKED: Final[int]
SQLITE_LOCKED_SHAREDCACHE: Final[int]
SQLITE_LOCKED_VTAB: Final[int]
SQLITE_MISMATCH: Final[int]
SQLITE_MISUSE: Final[int]
SQLITE_NOLFS: Final[int]
SQLITE_NOMEM: Final[int]
SQLITE_NOTADB: Final[int]
SQLITE_NOTFOUND: Final[int]
SQLITE_NOTICE: Final[int]
SQLITE_NOTICE_RECOVER_ROLLBACK: Final[int]
SQLITE_NOTICE_RECOVER_WAL: Final[int]
SQLITE_OK_LOAD_PERMANENTLY: Final[int]
SQLITE_OK_SYMLINK: Final[int]
SQLITE_PERM: Final[int]
SQLITE_PROTOCOL: Final[int]
SQLITE_RANGE: Final[int]
SQLITE_READONLY: Final[int]
SQLITE_READONLY_CANTINIT: Final[int]
SQLITE_READONLY_CANTLOCK: Final[int]
SQLITE_READONLY_DBMOVED: Final[int]
SQLITE_READONLY_DIRECTORY: Final[int]
SQLITE_READONLY_RECOVERY: Final[int]
SQLITE_READONLY_ROLLBACK: Final[int]
SQLITE_ROW: Final[int]
SQLITE_SCHEMA: Final[int]
SQLITE_TOOBIG: Final[int]
SQLITE_WARNING: Final[int]
SQLITE_WARNING_AUTOINDEX: Final[int]
threadsafety: Final[int]
# 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: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "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: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None,
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: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "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: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "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: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None,
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: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "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
def enable_shared_cache(do_enable: int) -> None: ...
if sys.version_info >= (3, 10):
def register_adapter(type: type[_T], adapter: _Adapter[_T], /) -> None: ...
def register_converter(typename: str, converter: _Converter, /) -> None: ...
else:
def register_adapter(type: type[_T], caster: _Adapter[_T], /) -> None: ...
def register_converter(name: str, converter: _Converter, /) -> None: ...
if sys.version_info < (3, 10):
OptimizedUnicode = str

View file

@ -0,0 +1,291 @@
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, Literal, TypedDict, final, overload
from typing_extensions import NotRequired, Self, TypeAlias
_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]
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 _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):
def RAND_pseudo_bytes(n: int, /) -> tuple[bytes, bool]: ...
if sys.version_info < (3, 10):
def RAND_egd(path: str) -> None: ...
def RAND_status() -> bool: ...
def get_default_verify_paths() -> tuple[str, str, str, 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]: ...
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
if sys.version_info >= (3, 10):
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, 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
if sys.version_info >= (3, 10):
@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: str
# SSL error numbers
SSL_ERROR_ZERO_RETURN: int
SSL_ERROR_WANT_READ: int
SSL_ERROR_WANT_WRITE: int
SSL_ERROR_WANT_X509_LOOKUP: int
SSL_ERROR_SYSCALL: int
SSL_ERROR_SSL: int
SSL_ERROR_WANT_CONNECT: int
SSL_ERROR_EOF: int
SSL_ERROR_INVALID_ERROR_CODE: int
# verify modes
CERT_NONE: int
CERT_OPTIONAL: int
CERT_REQUIRED: int
# verify flags
VERIFY_DEFAULT: int
VERIFY_CRL_CHECK_LEAF: int
VERIFY_CRL_CHECK_CHAIN: int
VERIFY_X509_STRICT: int
VERIFY_X509_TRUSTED_FIRST: int
if sys.version_info >= (3, 10):
VERIFY_ALLOW_PROXY_CERTS: int
VERIFY_X509_PARTIAL_CHAIN: int
# alert descriptions
ALERT_DESCRIPTION_CLOSE_NOTIFY: int
ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: int
ALERT_DESCRIPTION_BAD_RECORD_MAC: int
ALERT_DESCRIPTION_RECORD_OVERFLOW: int
ALERT_DESCRIPTION_DECOMPRESSION_FAILURE: int
ALERT_DESCRIPTION_HANDSHAKE_FAILURE: int
ALERT_DESCRIPTION_BAD_CERTIFICATE: int
ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: int
ALERT_DESCRIPTION_CERTIFICATE_REVOKED: int
ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: int
ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: int
ALERT_DESCRIPTION_ILLEGAL_PARAMETER: int
ALERT_DESCRIPTION_UNKNOWN_CA: int
ALERT_DESCRIPTION_ACCESS_DENIED: int
ALERT_DESCRIPTION_DECODE_ERROR: int
ALERT_DESCRIPTION_DECRYPT_ERROR: int
ALERT_DESCRIPTION_PROTOCOL_VERSION: int
ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: int
ALERT_DESCRIPTION_INTERNAL_ERROR: int
ALERT_DESCRIPTION_USER_CANCELLED: int
ALERT_DESCRIPTION_NO_RENEGOTIATION: int
ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: int
ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: int
ALERT_DESCRIPTION_UNRECOGNIZED_NAME: int
ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: int
ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: int
ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: int
# protocol versions
PROTOCOL_SSLv23: int
PROTOCOL_TLS: int
PROTOCOL_TLS_CLIENT: int
PROTOCOL_TLS_SERVER: int
PROTOCOL_TLSv1: int
PROTOCOL_TLSv1_1: int
PROTOCOL_TLSv1_2: int
# protocol options
OP_ALL: int
OP_NO_SSLv2: int
OP_NO_SSLv3: int
OP_NO_TLSv1: int
OP_NO_TLSv1_1: int
OP_NO_TLSv1_2: int
OP_NO_TLSv1_3: int
OP_CIPHER_SERVER_PREFERENCE: int
OP_SINGLE_DH_USE: int
OP_NO_TICKET: int
OP_SINGLE_ECDH_USE: int
OP_NO_COMPRESSION: int
OP_ENABLE_MIDDLEBOX_COMPAT: int
OP_NO_RENEGOTIATION: int
if sys.version_info >= (3, 11) or sys.platform == "linux":
OP_IGNORE_UNEXPECTED_EOF: int
if sys.version_info >= (3, 12):
OP_LEGACY_SERVER_CONNECT: int
OP_ENABLE_KTLS: int
# host flags
HOSTFLAG_ALWAYS_CHECK_SUBJECT: int
HOSTFLAG_NEVER_CHECK_SUBJECT: int
HOSTFLAG_NO_WILDCARDS: int
HOSTFLAG_NO_PARTIAL_WILDCARDS: int
HOSTFLAG_MULTI_LABEL_WILDCARDS: int
HOSTFLAG_SINGLE_LABEL_SUBDOMAINS: int
if sys.version_info >= (3, 10):
# certificate file types
# Typed as Literal so the overload on Certificate.public_bytes can work properly.
ENCODING_PEM: Literal[1]
ENCODING_DER: Literal[2]
# protocol versions
PROTO_MINIMUM_SUPPORTED: int
PROTO_MAXIMUM_SUPPORTED: int
PROTO_SSLv3: int
PROTO_TLSv1: int
PROTO_TLSv1_1: int
PROTO_TLSv1_2: int
PROTO_TLSv1_3: int
# feature support
HAS_SNI: bool
HAS_TLS_UNIQUE: bool
HAS_ECDH: bool
HAS_NPN: bool
if sys.version_info >= (3, 13):
HAS_PSK: bool
HAS_ALPN: bool
HAS_SSLv2: bool
HAS_SSLv3: bool
HAS_TLSv1: bool
HAS_TLSv1_1: bool
HAS_TLSv1_2: bool
HAS_TLSv1_3: bool
# version info
OPENSSL_VERSION_NUMBER: int
OPENSSL_VERSION_INFO: tuple[int, int, int, int, int]
OPENSSL_VERSION: str
_OPENSSL_API_VERSION: tuple[int, int, int, int, int]

View file

@ -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

View file

@ -0,0 +1,22 @@
from _typeshed import ReadableBuffer, WriteableBuffer
from collections.abc import Iterator
from typing import Any
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: ...
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, ...]]: ...

View file

@ -0,0 +1,111 @@
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, NoReturn, final, overload
from typing_extensions import TypeVarTuple, Unpack
_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, 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: ...
def acquire_lock(self, blocking: bool = True, timeout: float = -1) -> bool: ...
def release_lock(self) -> None: ...
def locked_lock(self) -> bool: ...
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: ...
def acquire_lock(self, blocking: bool = True, timeout: float = -1) -> bool: ...
def release_lock(self) -> None: ...
def locked_lock(self) -> bool: ...
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: ...
# Obsolete synonym for start_new_thread()
@overload
def start_new(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: ...
@overload
def start_new(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ...
if sys.version_info >= (3, 10):
def interrupt_main(signum: signal.Signals = ..., /) -> None: ...
else:
def interrupt_main() -> None: ...
def exit() -> NoReturn: ...
def exit_thread() -> NoReturn: ... # Obsolete synonym for exit()
def allocate_lock() -> LockType: ...
def allocate() -> LockType: ... # Obsolete synonym for allocate_lock()
def get_ident() -> int: ...
def stack_size(size: int = 0, /) -> int: ...
TIMEOUT_MAX: 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]):
if sys.version_info >= (3, 10):
__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: ...
class _local:
def __getattribute__(self, name: str, /) -> Any: ...
def __setattr__(self, name: str, value: Any, /) -> None: ...
def __delattr__(self, name: str, /) -> None: ...

View file

@ -0,0 +1,22 @@
from threading import RLock
from typing import Any
from typing_extensions import Self, TypeAlias
from weakref import ReferenceType
__all__ = ["local"]
_LocalDict: TypeAlias = dict[Any, Any]
class _localimpl:
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:
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: ...

View file

@ -0,0 +1,143 @@
import sys
from collections.abc import Callable
from typing import Any, ClassVar, Final, final
from typing_extensions import TypeAlias
# _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')
# (<textindex object: '1.0'>, <textindex object: '2.0'>)
@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, /): ...
def call(self, command: Any, /, *args: Any) -> Any: ...
def createcommand(self, name, func, /): ...
if sys.platform != "win32":
def createfilehandler(self, file, mask, func, /): ...
def deletefilehandler(self, file, /): ...
def createtimerhandler(self, milliseconds, func, /): ...
def deletecommand(self, name, /): ...
def dooneevent(self, flags: int = 0, /): ...
def eval(self, script: str, /) -> str: ...
def evalfile(self, fileName, /): ...
def exprboolean(self, s, /): ...
def exprdouble(self, s, /): ...
def exprlong(self, s, /): ...
def exprstring(self, s, /): ...
def getboolean(self, arg, /): ...
def getdouble(self, arg, /): ...
def getint(self, arg, /): ...
def getvar(self, *args, **kwargs): ...
def globalgetvar(self, *args, **kwargs): ...
def globalsetvar(self, *args, **kwargs): ...
def globalunsetvar(self, *args, **kwargs): ...
def interpaddr(self): ...
def loadtk(self) -> None: ...
def mainloop(self, threshold: int = 0, /): ...
def quit(self): ...
def record(self, script, /): ...
def setvar(self, *ags, **kwargs): ...
if sys.version_info < (3, 11):
def split(self, arg, /): ...
def splitlist(self, arg, /): ...
def unsetvar(self, *args, **kwargs): ...
def wantobjects(self, *args, **kwargs): ...
def willdispatch(self): ...
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): ...
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,
/,
): ...
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,
/,
): ...
def getbusywaitinterval(): ...
def setbusywaitinterval(new_val, /): ...

View file

@ -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: ...

View file

@ -0,0 +1,34 @@
# Utility types for typeshed
This package and its submodules contains 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.

View file

@ -0,0 +1,366 @@
# Utility types for typeshed
#
# See the README.md file in this directory for more information.
import sys
from collections.abc import Awaitable, Callable, Iterable, Sequence, Set as AbstractSet, Sized
from dataclasses import Field
from os import PathLike
from types import FrameType, TracebackType
from typing import (
Any,
AnyStr,
ClassVar,
Final,
Generic,
Literal,
Protocol,
SupportsFloat,
SupportsIndex,
SupportsInt,
TypeVar,
final,
overload,
)
from typing_extensions import Buffer, LiteralString, Self as _Self, TypeAlias
_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
# CONTRIBUTING.md for more information.
MaybeNone: TypeAlias = Any # stable
# 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)
# sentinel: _SentinelType
# def foo(x: int | None | _SentinelType = ...) -> None: ...
sentinel: Any
# 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]: ...
# Comparison protocols
class SupportsDunderLT(Protocol[_T_contra]):
def __lt__(self, other: _T_contra, /) -> bool: ...
class SupportsDunderGT(Protocol[_T_contra]):
def __gt__(self, other: _T_contra, /) -> bool: ...
class SupportsDunderLE(Protocol[_T_contra]):
def __le__(self, other: _T_contra, /) -> bool: ...
class SupportsDunderGE(Protocol[_T_contra]):
def __ge__(self, other: _T_contra, /) -> bool: ...
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 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 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: ...
# 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, /) -> 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, /) -> Sequence[int]: ...
@overload
def __getitem__(self, i: int, /) -> int: ...
class SizedBuffer(Sized, Buffer, Protocol): ...
# for compatibility with third-party stubs that may use this
_BufferWithLen: TypeAlias = SizedBuffer # not stable # noqa: Y047
ExcInfo: TypeAlias = tuple[type[BaseException], BaseException, TracebackType]
OptExcInfo: TypeAlias = ExcInfo | tuple[None, None, None]
# stable
if sys.version_info >= (3, 10):
from types import NoneType as NoneType
else:
# Used by type checkers for checks involving None (does not exist at runtime)
@final
class NoneType:
def __bool__(self) -> Literal[False]: ...
# 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, str, Any], object]
# Objects suitable to be passed to sys.settrace, threading.settrace, and similar
TraceFunction: TypeAlias = Callable[[FrameType, str, 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
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): ...

View file

@ -0,0 +1,37 @@
# 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
from typing_extensions import 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: ...

View file

@ -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: ...

View file

@ -0,0 +1,44 @@
# 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
from typing_extensions import 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]: ...

View file

@ -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: ...

View file

@ -0,0 +1,55 @@
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 = ...,
module_globals: dict[str, Any] | None = ...,
source: Any | None = ...,
) -> None: ...
@overload
def warn_explicit(
message: Warning,
category: Any,
filename: str,
lineno: int,
module: str | None = ...,
registry: dict[str | tuple[str, type[Warning], int], int] | None = ...,
module_globals: dict[str, Any] | None = ...,
source: Any | None = ...,
) -> None: ...

View file

@ -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: ...

View file

@ -0,0 +1,48 @@
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: ...

View file

@ -0,0 +1,283 @@
import sys
from _typeshed import ReadableBuffer
from collections.abc import Sequence
from typing import Any, Final, Literal, NoReturn, final, overload
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
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
if sys.version_info >= (3, 10):
LOCALE_NAME_INVARIANT: str
LOCALE_NAME_MAX_LENGTH: int
LOCALE_NAME_SYSTEM_DEFAULT: str
LOCALE_NAME_USER_DEFAULT: str | None
LCMAP_FULLWIDTH: int
LCMAP_HALFWIDTH: int
LCMAP_HIRAGANA: int
LCMAP_KATAKANA: int
LCMAP_LINGUISTIC_CASING: int
LCMAP_LOWERCASE: int
LCMAP_SIMPLIFIED_CHINESE: int
LCMAP_TITLECASE: int
LCMAP_TRADITIONAL_CHINESE: int
LCMAP_UPPERCASE: 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
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 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, /) -> NoReturn: ...
def GetACP() -> 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 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]: ...
if sys.version_info >= (3, 10):
def LCMapStringEx(locale: str, flags: int, src: str) -> str: ...
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 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: ...
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: ...

View file

@ -0,0 +1,51 @@
import _typeshed
import sys
from _typeshed import SupportsWrite
from collections.abc import Callable
from typing import Any, Literal, TypeVar
from typing_extensions import Concatenate, ParamSpec, 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("Use 'classmethod' with '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("Use 'staticmethod' with 'abstractmethod' instead")
class abstractstaticmethod(staticmethod[_P, _R_co]):
__isabstractmethod__: Literal[True]
def __init__(self, callable: Callable[_P, _R_co]) -> None: ...
@deprecated("Use 'property' with 'abstractmethod' instead")
class abstractproperty(property):
__isabstractmethod__: Literal[True]
class ABC(metaclass=ABCMeta):
__slots__ = ()
def get_cache_token() -> object: ...
if sys.version_info >= (3, 10):
def update_abstractmethods(cls: type[_T]) -> type[_T]: ...

View file

@ -0,0 +1,79 @@
from types import TracebackType
from typing import IO, Any, Literal, NamedTuple, overload
from typing_extensions import Self, TypeAlias
__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: ...

View file

@ -0,0 +1,3 @@
from _typeshed import ReadableBuffer
def geohash(latitude: float, longitude: float, datedow: ReadableBuffer) -> None: ...

View file

@ -0,0 +1,725 @@
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, NoReturn, Protocol, TypeVar, overload
from typing_extensions import Self, TypeAlias, 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[_T] | None = ...,
required: bool = ...,
help: str | None = ...,
metavar: str | tuple[str, ...] | None = ...,
dest: str | None = ...,
version: str = ...,
**kwargs: Any,
) -> Action: ...
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]]) -> NoReturn: ...
def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> None: ...
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
# undocumented
_positionals: _ArgumentGroup
_optionals: _ArgumentGroup
_subparsers: _ArgumentGroup | None
# Note: the constructor arguments are also used in _SubParsersAction.add_parser.
def __init__(
self,
prog: str | None = None,
usage: str | None = None,
description: str | None = None,
epilog: str | None = None,
parents: Sequence[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: Sequence[str] | None = None, namespace: None = None) -> Namespace: ...
@overload
def parse_args(self, args: Sequence[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: ...
def format_usage(self) -> str: ...
def format_help(self) -> str: ...
@overload
def parse_known_args(self, args: Sequence[str] | None = None, namespace: None = None) -> tuple[Namespace, list[str]]: ...
@overload
def parse_known_args(self, args: Sequence[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) -> NoReturn: ...
def error(self, message: str) -> NoReturn: ...
@overload
def parse_intermixed_args(self, args: Sequence[str] | None = None, namespace: None = None) -> Namespace: ...
@overload
def parse_intermixed_args(self, args: Sequence[str] | None, namespace: _N) -> _N: ...
@overload
def parse_intermixed_args(self, *, namespace: _N) -> _N: ...
@overload
def parse_known_intermixed_args(
self, args: Sequence[str] | None = None, namespace: None = None
) -> tuple[Namespace, list[str]]: ...
@overload
def parse_known_intermixed_args(self, args: Sequence[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]: ...
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: ...
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
_current_section: _Section
_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: ...
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: ...
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, None, None]: ...
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]
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]
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, 13):
def add_parser(
self,
name: str,
*,
deprecated: bool = False,
help: str | None = ...,
aliases: Sequence[str] = ...,
# Kwargs from ArgumentParser constructor
prog: str | None = ...,
usage: str | None = ...,
description: str | None = ...,
epilog: str | None = ...,
parents: Sequence[_ArgumentParserT] = ...,
formatter_class: _FormatterClass = ...,
prefix_chars: str = ...,
fromfile_prefix_chars: str | None = ...,
argument_default: Any = ...,
conflict_handler: str = ...,
add_help: bool = ...,
allow_abbrev: bool = ...,
exit_on_error: bool = ...,
**kwargs: Any, # Accepting any additional kwargs for custom parser classes
) -> _ArgumentParserT: ...
else:
def add_parser(
self,
name: str,
*,
help: str | None = ...,
aliases: Sequence[str] = ...,
# Kwargs from ArgumentParser constructor
prog: str | None = ...,
usage: str | None = ...,
description: str | None = ...,
epilog: str | None = ...,
parents: Sequence[_ArgumentParserT] = ...,
formatter_class: _FormatterClass = ...,
prefix_chars: str = ...,
fromfile_prefix_chars: str | None = ...,
argument_default: Any = ...,
conflict_handler: str = ...,
add_help: bool = ...,
allow_abbrev: bool = ...,
exit_on_error: bool = ...,
**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: ...

View file

@ -0,0 +1,88 @@
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, TypeVar, overload
from typing_extensions import Self, TypeAlias
_IntTypeCode: TypeAlias = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"]
_FloatTypeCode: TypeAlias = Literal["f", "d"]
_UnicodeTypeCode: TypeAlias = Literal["u"]
_TypeCode: TypeAlias = _IntTypeCode | _FloatTypeCode | _UnicodeTypeCode
_T = TypeVar("_T", int, float, str)
typecodes: str
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]: ...
@overload
def __new__(
cls: type[array[str]], typecode: _UnicodeTypeCode, 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: ...
if sys.version_info >= (3, 10):
def index(self, v: _T, start: int = 0, stop: int = sys.maxsize, /) -> int: ...
else:
def index(self, v: _T, /) -> int: ... # type: ignore[override]
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 __len__(self) -> int: ...
@overload
def __getitem__(self, key: SupportsIndex, /) -> _T: ...
@overload
def __getitem__(self, key: slice, /) -> array[_T]: ...
@overload # type: ignore[override]
def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ...
@overload
def __setitem__(self, key: slice, value: array[_T], /) -> None: ...
def __delitem__(self, key: SupportsIndex | slice, /) -> 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

File diff suppressed because it is too large Load diff

View file

@ -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: ...

View file

@ -0,0 +1,990 @@
# ruff: noqa: PLR5501 # 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, TypeVar
from typing_extensions import TypeAlias
# 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, 11):
from .taskgroups import *
from .timeouts import *
if sys.platform == "win32":
from .windows_events import *
else:
from .unix_events import *
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
"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
"_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, 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
"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
"_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
"DefaultEventLoopPolicy", # 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]

View file

@ -0,0 +1,488 @@
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, SocketKind, _Address, _RetAddress, socket
from typing import IO, Any, Literal, TypeVar, overload
from typing_extensions import TypeAlias, 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
if 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,
) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ...
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 = ...,
flags: int = ...,
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 = ...,
flags: int = ...,
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 = ...,
flags: int = ...,
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 = ...,
flags: int = ...,
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 = ...,
flags: int = ...,
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 = ...,
flags: int = ...,
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: ...

View file

@ -0,0 +1,19 @@
from collections.abc import Callable, Sequence
from contextvars import Context
from typing import Any, Final
from . import futures
__all__ = ()
# asyncio defines 'isfuture()' in base_futures.py and re-imports it in futures.py
# but it leads to circular import error in pytype tool.
# That's why the import order is reversed.
from .futures import isfuture as isfuture
_PENDING: Final = "PENDING" # undocumented
_CANCELLED: Final = "CANCELLED" # undocumented
_FINISHED: Final = "FINISHED" # undocumented
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

View file

@ -0,0 +1,63 @@
import subprocess
from collections import deque
from collections.abc import Callable, Sequence
from typing import IO, Any
from typing_extensions import 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

View file

@ -0,0 +1,9 @@
from _typeshed import StrOrBytesPath
from types import FrameType
from typing import Any
from . import tasks
def _task_repr_info(task: tasks.Task[Any]) -> list[str]: ... # undocumented
def _task_get_stack(task: tasks.Task[Any], limit: int | None) -> list[FrameType]: ... # undocumented
def _task_print_stack(task: tasks.Task[Any], limit: int | None, file: StrOrBytesPath) -> None: ... # undocumented

View file

@ -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

View file

@ -0,0 +1,27 @@
import sys
from collections.abc import Awaitable, Callable, Coroutine
from typing import Any, TypeVar, overload
from typing_extensions import ParamSpec, TypeGuard, TypeIs
# 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):
def coroutine(func: _FunctionT) -> _FunctionT: ...
@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]]]: ...
def iscoroutine(obj: object) -> TypeIs[Coroutine[Any, Any, Any]]: ...

View file

@ -0,0 +1,642 @@
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, SocketKind, _Address, _RetAddress, socket
from typing import IO, Any, Literal, Protocol, TypeVar, overload
from typing_extensions import Self, TypeAlias, 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
from .unix_events import AbstractChildWatcher
# Keep asyncio.__all__ updated with any changes to __all__ here
if sys.version_info >= (3, 14):
__all__ = (
"AbstractEventLoopPolicy",
"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
class _TaskFactory(Protocol):
def __call__(self, loop: AbstractEventLoop, factory: _CoroutineLike[_T], /) -> Future[_T]: ...
class Handle:
_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):
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
if 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,
) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ...
@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 = ...,
flags: int = ...,
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 = ...,
flags: int = ...,
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 = ...,
flags: int = ...,
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 = ...,
flags: int = ...,
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 = ...,
flags: int = ...,
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 = ...,
flags: int = ...,
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]: ...
elif sys.version_info >= (3, 10):
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 = ...,
**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: ...
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).
if sys.version_info < (3, 14):
if sys.version_info >= (3, 12):
@abstractmethod
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
def get_child_watcher(self) -> AbstractChildWatcher: ...
@abstractmethod
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ...
else:
@abstractmethod
def get_child_watcher(self) -> AbstractChildWatcher: ...
@abstractmethod
def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ...
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: ...
def get_event_loop_policy() -> AbstractEventLoopPolicy: ...
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):
if sys.version_info >= (3, 12):
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
def get_child_watcher() -> AbstractChildWatcher: ...
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
def set_child_watcher(watcher: AbstractChildWatcher) -> None: ...
else:
def get_child_watcher() -> AbstractChildWatcher: ...
def set_child_watcher(watcher: AbstractChildWatcher) -> None: ...

View file

@ -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): ...

View file

@ -0,0 +1,31 @@
import functools
import sys
import traceback
from collections.abc import Iterable
from types import FrameType, FunctionType
from typing import Any, overload
from typing_extensions import TypeAlias
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: ...

View file

@ -0,0 +1,17 @@
from _asyncio import Future as Future
from concurrent.futures._base import Future as _ConcurrentFuture
from typing import Any, TypeVar
from typing_extensions import TypeIs
from .events import AbstractEventLoop
# Keep asyncio.__all__ updated with any changes to __all__ here
__all__ = ("Future", "wrap_future", "isfuture")
_T = TypeVar("_T")
# asyncio defines 'isfuture()' in base_futures.py and re-imports it in futures.py
# but it leads to circular import error in pytype tool.
# That's why the import order is reversed.
def isfuture(obj: object) -> TypeIs[Future[Any]]: ...
def wrap_future(future: _ConcurrentFuture[_T] | Future[_T], *, loop: AbstractEventLoop | None = None) -> Future[_T]: ...

View file

@ -0,0 +1,104 @@
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 .events import AbstractEventLoop
from .futures import Future
if sys.version_info >= (3, 10):
from .mixins import _LoopBoundMixin
else:
_LoopBoundMixin = object
# 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
if sys.version_info >= (3, 10):
def __init__(self) -> None: ...
else:
def __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ...
def locked(self) -> bool: ...
async def acquire(self) -> Literal[True]: ...
def release(self) -> None: ...
class Event(_LoopBoundMixin):
_waiters: deque[Future[Any]]
if sys.version_info >= (3, 10):
def __init__(self) -> None: ...
else:
def __init__(self, *, loop: AbstractEventLoop | None = None) -> 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]]
if sys.version_info >= (3, 10):
def __init__(self, lock: Lock | None = None) -> None: ...
else:
def __init__(self, lock: Lock | None = None, *, loop: AbstractEventLoop | 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
if sys.version_info >= (3, 10):
def __init__(self, value: int = 1) -> None: ...
else:
def __init__(self, value: int = 1, *, loop: AbstractEventLoop | None = None) -> 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: ...

View file

@ -0,0 +1,3 @@
import logging
logger: logging.Logger

View file

@ -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: ...

View file

@ -0,0 +1,65 @@
import sys
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):
if sys.version_info >= (3, 10):
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: ...
else:
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: ...
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: ...

View file

@ -0,0 +1,35 @@
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:
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):
def data_received(self, data: bytes) -> None: ...
def eof_received(self) -> bool | None: ...
class BufferedProtocol(BaseProtocol):
def get_buffer(self, sizehint: int) -> ReadableBuffer: ...
def buffer_updated(self, nbytes: int) -> None: ...
def eof_received(self) -> bool | None: ...
class DatagramProtocol(BaseProtocol):
def connection_made(self, transport: transports.DatagramTransport) -> None: ... # type: ignore[override]
# addr can be a tuple[int, int] for some unusual protocols like socket.AF_NETLINK.
# Use tuple[str | Any, int] to not cause typechecking issues on most usual cases.
# This could be improved by using tuple[AnyOf[str, int], int] if the AnyOf feature is accepted.
# See https://github.com/python/typing/issues/566
def datagram_received(self, data: bytes, addr: tuple[str | Any, int]) -> None: ...
def error_received(self, exc: Exception) -> None: ...
class SubprocessProtocol(BaseProtocol):
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: ...

View file

@ -0,0 +1,54 @@
import sys
from asyncio.events import AbstractEventLoop
from types import GenericAlias
from typing import Any, Generic, TypeVar
if sys.version_info >= (3, 10):
from .mixins import _LoopBoundMixin
else:
_LoopBoundMixin = object
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): ...
# If Generic[_T] is last and _LoopBoundMixin is object, pyright is unhappy.
# We can remove the noqa pragma when dropping 3.9 support.
class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059
if sys.version_info >= (3, 10):
def __init__(self, maxsize: int = 0) -> None: ...
else:
def __init__(self, maxsize: int = 0, *, loop: AbstractEventLoop | None = None) -> 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[_T]): ...
class LifoQueue(Queue[_T]): ...

View file

@ -0,0 +1,33 @@
import sys
from _typeshed import Unused
from collections.abc import 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: ...
def run(self, coro: Coroutine[Any, Any, _T], *, context: Context | None = None) -> _T: ...
if sys.version_info >= (3, 12):
def run(
main: Coroutine[Any, Any, _T], *, debug: bool | None = ..., loop_factory: Callable[[], AbstractEventLoop] | None = ...
) -> _T: ...
else:
def run(main: Coroutine[Any, Any, _T], *, debug: bool | None = None) -> _T: ...

Some files were not shown because too many files have changed in this diff Show more