0
# Standard Library Stubs
1
2
Comprehensive type stubs for Python's standard library modules, providing type annotations for core functionality including data structures, I/O operations, networking, concurrency, system interfaces, and more.
3
4
## Capabilities
5
6
### Core Data Types and Collections
7
8
Type stubs for Python's fundamental data structures and collection types.
9
10
```python { .api }
11
# Built-in types with enhanced type information
12
from typing import Dict, List, Set, Tuple, Optional, Union, Any
13
from collections import defaultdict, deque, Counter, OrderedDict
14
from collections.abc import Mapping, Sequence, Iterable, Iterator
15
16
# Example stub signatures:
17
def dict(*args, **kwargs) -> Dict[Any, Any]: ...
18
def list(iterable: Iterable[_T] = ...) -> List[_T]: ...
19
def set(iterable: Iterable[_T] = ...) -> Set[_T]: ...
20
def tuple(iterable: Iterable[_T] = ...) -> Tuple[_T, ...]: ...
21
```
22
23
### File System and I/O Operations
24
25
Type annotations for file handling, path operations, and I/O streams.
26
27
```python { .api }
28
import os
29
import pathlib
30
import io
31
from typing import Union, Optional, AnyStr, TextIO, BinaryIO
32
33
# Path operations
34
def os.path.join(path: AnyStr, *paths: AnyStr) -> AnyStr: ...
35
def os.path.exists(path: Union[str, bytes, os.PathLike[Any]]) -> bool: ...
36
def os.listdir(path: Union[str, bytes, os.PathLike[Any]] = '.') -> List[str]: ...
37
38
# File operations
39
def open(
40
file: Union[str, bytes, os.PathLike[Any], int],
41
mode: str = 'r',
42
buffering: int = -1,
43
encoding: Optional[str] = None,
44
errors: Optional[str] = None,
45
newline: Optional[str] = None,
46
closefd: bool = True,
47
opener: Optional[Callable[[str, int], int]] = None
48
) -> Union[TextIO, BinaryIO]: ...
49
```
50
51
### Asynchronous Programming
52
53
Type stubs for asyncio and concurrent programming primitives.
54
55
```python { .api }
56
import asyncio
57
from typing import TypeVar, Generic, Coroutine, Awaitable, Optional, Any
58
from collections.abc import Callable
59
60
_T = TypeVar('_T')
61
62
# Core asyncio functions
63
def asyncio.run(main: Awaitable[_T], *, debug: Optional[bool] = None) -> _T: ...
64
def asyncio.create_task(coro: Coroutine[Any, Any, _T]) -> asyncio.Task[_T]: ...
65
def asyncio.gather(*aws: Awaitable[Any], return_exceptions: bool = False) -> Coroutine[Any, Any, List[Any]]: ...
66
67
# Event loop operations
68
class AbstractEventLoop:
69
def run_until_complete(self, future: Awaitable[_T]) -> _T: ...
70
def create_future(self) -> asyncio.Future[Any]: ...
71
def create_task(self, coro: Coroutine[Any, Any, _T]) -> asyncio.Task[_T]: ...
72
```
73
74
### Network and Internet Protocols
75
76
Type annotations for HTTP, URL handling, and network operations.
77
78
```python { .api }
79
import urllib.request
80
import urllib.parse
81
import http.client
82
from typing import Optional, Dict, List, Union, Any, Mapping
83
84
# URL operations
85
def urllib.parse.urlparse(urlstring: str) -> urllib.parse.ParseResult: ...
86
def urllib.parse.urljoin(base: str, url: str) -> str: ...
87
def urllib.parse.quote(string: str, safe: str = '/', encoding: str = 'utf-8') -> str: ...
88
89
# HTTP client
90
class http.client.HTTPConnection:
91
def __init__(
92
self,
93
host: str,
94
port: Optional[int] = None,
95
timeout: Optional[float] = None,
96
source_address: Optional[Tuple[str, int]] = None
97
) -> None: ...
98
def request(self, method: str, url: str, body: Optional[Union[str, bytes]] = None, headers: Mapping[str, str] = {}) -> None: ...
99
def getresponse(self) -> http.client.HTTPResponse: ...
100
```
101
102
### Regular Expressions
103
104
Type stubs for pattern matching and text processing.
105
106
```python { .api }
107
import re
108
from typing import AnyStr, Optional, List, Iterator, Pattern, Match, Union
109
110
# Pattern compilation and matching
111
def re.compile(pattern: AnyStr, flags: int = 0) -> Pattern[AnyStr]: ...
112
def re.match(pattern: AnyStr, string: AnyStr, flags: int = 0) -> Optional[Match[AnyStr]]: ...
113
def re.search(pattern: AnyStr, string: AnyStr, flags: int = 0) -> Optional[Match[AnyStr]]: ...
114
def re.findall(pattern: AnyStr, string: AnyStr, flags: int = 0) -> List[Any]: ...
115
def re.finditer(pattern: AnyStr, string: AnyStr, flags: int = 0) -> Iterator[Match[AnyStr]]: ...
116
117
# Pattern and Match objects
118
class Pattern(Generic[AnyStr]):
119
def match(self, string: AnyStr, pos: int = 0, endpos: int = ...) -> Optional[Match[AnyStr]]: ...
120
def search(self, string: AnyStr, pos: int = 0, endpos: int = ...) -> Optional[Match[AnyStr]]: ...
121
def findall(self, string: AnyStr, pos: int = 0, endpos: int = ...) -> List[Any]: ...
122
```
123
124
### JSON Processing
125
126
Type annotations for JSON encoding and decoding operations.
127
128
```python { .api }
129
import json
130
from typing import Any, Optional, Union, TextIO, Dict, List, Callable
131
132
# JSON serialization
133
def json.dumps(
134
obj: Any,
135
*,
136
skipkeys: bool = False,
137
ensure_ascii: bool = True,
138
check_circular: bool = True,
139
allow_nan: bool = True,
140
cls: Optional[type] = None,
141
indent: Optional[Union[int, str]] = None,
142
separators: Optional[Tuple[str, str]] = None,
143
default: Optional[Callable[[Any], Any]] = None,
144
sort_keys: bool = False,
145
**kwds: Any
146
) -> str: ...
147
148
def json.loads(
149
s: Union[str, bytes, bytearray],
150
*,
151
cls: Optional[type] = None,
152
object_hook: Optional[Callable[[Dict[str, Any]], Any]] = None,
153
parse_float: Optional[Callable[[str], Any]] = None,
154
parse_int: Optional[Callable[[str], Any]] = None,
155
parse_constant: Optional[Callable[[str], Any]] = None,
156
object_pairs_hook: Optional[Callable[[List[Tuple[str, Any]]], Any]] = None,
157
**kwds: Any
158
) -> Any: ...
159
```
160
161
### Threading and Concurrency
162
163
Type stubs for thread-based parallelism and synchronization primitives.
164
165
```python { .api }
166
import threading
167
from typing import Optional, Any, Callable, ContextManager
168
from types import TracebackType
169
170
# Thread management
171
class threading.Thread:
172
def __init__(
173
self,
174
group: None = None,
175
target: Optional[Callable[..., Any]] = None,
176
name: Optional[str] = None,
177
args: Tuple[Any, ...] = (),
178
kwargs: Optional[Dict[str, Any]] = None,
179
daemon: Optional[bool] = None
180
) -> None: ...
181
def start(self) -> None: ...
182
def join(self, timeout: Optional[float] = None) -> None: ...
183
def is_alive(self) -> bool: ...
184
185
# Synchronization primitives
186
class threading.Lock:
187
def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ...
188
def release(self) -> None: ...
189
def __enter__(self) -> bool: ...
190
def __exit__(self, exc_type: Optional[type], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: ...
191
```
192
193
### System and OS Interface
194
195
Type annotations for system calls, environment variables, and process management.
196
197
```python { .api }
198
import sys
199
import os
200
from typing import List, Dict, Optional, Union, Any, NoReturn, TextIO
201
202
# System information
203
sys.version: str
204
sys.version_info: sys.VersionInfo
205
sys.platform: str
206
sys.argv: List[str]
207
sys.path: List[str]
208
sys.stdout: TextIO
209
sys.stderr: TextIO
210
sys.stdin: TextIO
211
212
# Process management
213
def sys.exit(code: Union[int, str, None] = None) -> NoReturn: ...
214
def os.getpid() -> int: ...
215
def os.getenv(key: str, default: Optional[str] = None) -> Optional[str]: ...
216
def os.environ.__getitem__(key: str) -> str: ...
217
def os.environ.__setitem__(key: str, value: str) -> None: ...
218
```
219
220
### Math and Numeric Operations
221
222
Type stubs for mathematical functions and numeric computations.
223
224
```python { .api }
225
import math
226
import random
227
from typing import Union, Optional, Sequence, SupportsFloat
228
229
# Mathematical functions
230
def math.sqrt(x: SupportsFloat) -> float: ...
231
def math.sin(x: SupportsFloat) -> float: ...
232
def math.cos(x: SupportsFloat) -> float: ...
233
def math.log(x: SupportsFloat, base: SupportsFloat = ...) -> float: ...
234
def math.pow(x: SupportsFloat, y: SupportsFloat) -> float: ...
235
236
# Random number generation
237
def random.random() -> float: ...
238
def random.randint(a: int, b: int) -> int: ...
239
def random.choice(seq: Sequence[_T]) -> _T: ...
240
def random.shuffle(x: List[Any], random: Optional[Callable[[], float]] = None) -> None: ...
241
```
242
243
## Error Handling
244
245
Standard library modules define specific exception types with proper inheritance hierarchies:
246
247
```python
248
# Example exception hierarchy stubs
249
class Exception(BaseException): ...
250
class ValueError(Exception): ...
251
class TypeError(Exception): ...
252
class FileNotFoundError(OSError): ...
253
class ConnectionError(OSError): ...
254
```
255
256
## Version Compatibility
257
258
Standard library stubs handle version differences through conditional imports:
259
260
```python
261
import sys
262
from typing import TYPE_CHECKING
263
264
if sys.version_info >= (3, 10):
265
from typing import TypeAlias, ParamSpec
266
else:
267
from typing_extensions import TypeAlias, ParamSpec
268
269
if sys.version_info >= (3, 11):
270
from typing import Self
271
else:
272
from typing_extensions import Self
273
```