0
# Typing Compatibility
1
2
Enhanced typing module compatibility layer with optimizations and forward compatibility features. The `beartype.typing` module provides all standard typing attributes with performance improvements and preservation of deprecated features for future Python versions.
3
4
## Capabilities
5
6
### Forward Compatibility
7
8
Preserve PEP 585-deprecated typing attributes to maintain compatibility with future Python versions.
9
10
```python { .api }
11
# PEP 585 deprecated attributes preserved for forward compatibility
12
from beartype.typing import (
13
Dict, List, Set, FrozenSet, Tuple, Type,
14
Callable, Collection, Container, Mapping, Sequence,
15
Iterable, Iterator, Generator, Coroutine,
16
AsyncIterable, AsyncIterator, AsyncGenerator,
17
Match, Pattern, AbstractSet, ChainMap, Counter,
18
DefaultDict, Deque, OrderedDict
19
)
20
```
21
22
Usage examples:
23
24
```python
25
from beartype.typing import List, Dict, Optional
26
from beartype import beartype
27
28
# Works across all Python versions
29
@beartype
30
def process_data(items: List[str]) -> Dict[str, int]:
31
return {item: len(item) for item in items}
32
33
@beartype
34
def merge_configs(
35
primary: Dict[str, str],
36
secondary: Optional[Dict[str, str]] = None
37
) -> Dict[str, str]:
38
if secondary:
39
return {**primary, **secondary}
40
return primary
41
```
42
43
### Standard Typing Attributes
44
45
All standard typing module attributes are available through beartype.typing.
46
47
```python { .api }
48
# Core typing attributes
49
from beartype.typing import (
50
Any, Union, Optional, Final, ClassVar,
51
TypeVar, Generic, Protocol, Literal,
52
Annotated, ForwardRef, NewType,
53
get_type_hints, get_origin, get_args,
54
cast, overload, no_type_check
55
)
56
```
57
58
### Version-Aware Imports
59
60
Conditional imports based on Python version with automatic fallbacks.
61
62
```python { .api }
63
# Python 3.10+ features
64
from beartype.typing import (
65
TypeAlias, TypeGuard, ParamSpec, Concatenate,
66
ParamSpecArgs, ParamSpecKwargs, is_typeddict
67
)
68
69
# Python 3.11+ features
70
from beartype.typing import (
71
Self, LiteralString, Never, NotRequired, Required,
72
TypeVarTuple, Unpack, assert_never, assert_type,
73
reveal_type, dataclass_transform
74
)
75
76
# Python 3.12+ features
77
from beartype.typing import (
78
TypeAliasType, override
79
)
80
81
# Python 3.13+ features
82
from beartype.typing import (
83
TypeIs, ReadOnly, NoDefault,
84
get_protocol_members, is_protocol
85
)
86
```
87
88
### Optimized Protocol Support
89
90
Enhanced Protocol implementation with better runtime performance.
91
92
```python { .api }
93
from beartype.typing import Protocol, runtime_checkable
94
95
@runtime_checkable
96
class Drawable(Protocol):
97
def draw(self) -> str: ...
98
99
# Optimized protocol checking
100
class Circle:
101
def draw(self) -> str:
102
return "Drawing circle"
103
104
# More efficient isinstance checks
105
assert isinstance(Circle(), Drawable)
106
```
107
108
Usage examples:
109
110
```python
111
from beartype.typing import Protocol, runtime_checkable
112
from beartype import beartype
113
114
@runtime_checkable
115
class Serializable(Protocol):
116
def serialize(self) -> dict: ...
117
def deserialize(self, data: dict) -> None: ...
118
119
@beartype
120
def save_object(obj: Serializable) -> dict:
121
return obj.serialize()
122
123
class User:
124
def __init__(self, name: str):
125
self.name = name
126
127
def serialize(self) -> dict:
128
return {"name": self.name}
129
130
def deserialize(self, data: dict) -> None:
131
self.name = data["name"]
132
133
user = User("Alice")
134
data = save_object(user) # Protocol automatically satisfied
135
```
136
137
### Type Construction Utilities
138
139
Utilities for creating and manipulating type hints programmatically.
140
141
```python { .api }
142
from beartype.typing import get_type_hints, get_origin, get_args
143
144
def inspect_function_types(func):
145
"""Inspect function's type hints."""
146
hints = get_type_hints(func)
147
for name, hint in hints.items():
148
origin = get_origin(hint)
149
args = get_args(hint)
150
print(f"{name}: {hint} (origin: {origin}, args: {args})")
151
```
152
153
### Deprecated Attribute Handling
154
155
Automatic handling of deprecated typing attributes with warnings.
156
157
```python { .api }
158
# Deprecated attributes still available with warnings
159
from beartype.typing import ByteString, AnyStr
160
161
# These will work but may emit deprecation warnings in future versions
162
@beartype
163
def process_bytes(data: ByteString) -> int:
164
return len(data)
165
166
@beartype
167
def concat_strings(a: AnyStr, b: AnyStr) -> AnyStr:
168
return a + b
169
```
170
171
### Type Checking Integration
172
173
Integration with static type checkers while providing runtime optimizations.
174
175
```python { .api }
176
from beartype.typing import TYPE_CHECKING
177
178
if TYPE_CHECKING:
179
# Import expensive types only for static analysis
180
from typing_extensions import TypedDict
181
182
class ConfigDict(TypedDict):
183
host: str
184
port: int
185
debug: bool
186
else:
187
# Runtime uses regular dict
188
ConfigDict = dict
189
```
190
191
### Collection Type Aliases
192
193
Enhanced collection type aliases with better runtime performance.
194
195
```python { .api }
196
from beartype.typing import (
197
Mapping, MutableMapping, Sequence, MutableSequence,
198
Set, MutableSet, ItemsView, KeysView, ValuesView,
199
Collection, Container, Sized, Iterable, Iterator,
200
Reversible, Hashable
201
)
202
```
203
204
Usage examples:
205
206
```python
207
from beartype.typing import Mapping, Sequence, Set
208
from beartype import beartype
209
210
@beartype
211
def analyze_data(
212
config: Mapping[str, str],
213
items: Sequence[int],
214
tags: Set[str]
215
) -> dict:
216
return {
217
"config_keys": len(config),
218
"item_count": len(items),
219
"unique_tags": len(tags)
220
}
221
222
# Works with any mapping, sequence, or set type
223
result = analyze_data(
224
{"host": "localhost", "port": "8080"}, # dict → Mapping
225
[1, 2, 3, 4, 5], # list → Sequence
226
{"python", "typing", "beartype"} # set → Set
227
)
228
```
229
230
### Advanced Type Features
231
232
Support for advanced typing features across Python versions.
233
234
```python { .api }
235
from beartype.typing import (
236
Callable, Awaitable, Coroutine, Generator,
237
AsyncIterable, AsyncIterator, AsyncGenerator,
238
ContextManager, AsyncContextManager
239
)
240
```
241
242
Usage examples:
243
244
```python
245
from beartype.typing import Callable, Generator, AsyncIterable
246
from beartype import beartype
247
import asyncio
248
249
@beartype
250
def apply_function(func: Callable[[int], str], value: int) -> str:
251
return func(value)
252
253
@beartype
254
def number_generator(start: int, end: int) -> Generator[int, None, None]:
255
for i in range(start, end):
256
yield i
257
258
@beartype
259
async def process_async_data(
260
data: AsyncIterable[str]
261
) -> list[str]:
262
results = []
263
async for item in data:
264
results.append(item.upper())
265
return results
266
267
# Usage
268
result = apply_function(str, 42) # "42"
269
270
gen = number_generator(1, 5)
271
numbers = list(gen) # [1, 2, 3, 4]
272
```
273
274
### Best Practices
275
276
#### Consistent Imports
277
278
Always import typing attributes from `beartype.typing` for consistency:
279
280
```python
281
# Recommended
282
from beartype.typing import List, Dict, Optional, Union
283
284
# Instead of mixing
285
from typing import List, Dict
286
from beartype.typing import Optional, Union
287
```
288
289
#### Version Compatibility
290
291
Use version checks when needed for conditional features:
292
293
```python
294
from beartype.typing import TYPE_CHECKING
295
import sys
296
297
if sys.version_info >= (3, 10):
298
from beartype.typing import TypeAlias
299
ConfigType: TypeAlias = dict[str, str]
300
else:
301
ConfigType = dict
302
```
303
304
#### Performance Considerations
305
306
Leverage beartype.typing's optimizations for better runtime performance:
307
308
```python
309
# Optimized protocol checking
310
from beartype.typing import Protocol, runtime_checkable
311
312
@runtime_checkable
313
class FastProtocol(Protocol):
314
def method(self) -> int: ...
315
316
# More efficient than typing.Protocol
317
def check_object(obj):
318
return isinstance(obj, FastProtocol)
319
```