0
# Import Hooks
1
2
Automatic decoration of packages and modules using PEP 302/451-compliant import hooks. The `beartype.claw` module provides powerful mechanisms to automatically apply beartype decoration to entire packages or the complete Python ecosystem without manually decorating individual functions.
3
4
## Capabilities
5
6
### Global Package Decoration
7
8
Apply beartype to all importable packages in the Python ecosystem.
9
10
```python { .api }
11
def beartype_all(conf=None):
12
"""
13
Apply beartype to all importable packages.
14
15
Automatically decorates all annotated functions in all packages
16
imported after this call.
17
18
Parameters:
19
- conf: BeartypeConf - Optional configuration (defaults to BeartypeConf())
20
21
Returns:
22
None
23
"""
24
```
25
26
Usage examples:
27
28
```python
29
from beartype.claw import beartype_all
30
from beartype import BeartypeConf, BeartypeStrategy
31
32
# Apply to all packages with default configuration
33
beartype_all()
34
35
# Apply with custom configuration
36
beartype_all(conf=BeartypeConf(
37
strategy=BeartypeStrategy.On,
38
is_debug=True
39
))
40
41
# Now all annotated functions in any imported package are type-checked
42
import some_package # All functions automatically decorated
43
```
44
45
### Single Package Decoration
46
47
Apply beartype to a specific named package.
48
49
```python { .api }
50
def beartype_package(package_name, conf=None):
51
"""
52
Apply beartype to a specific package by name.
53
54
Parameters:
55
- package_name: str - Name of package to decorate
56
- conf: BeartypeConf - Optional configuration
57
58
Returns:
59
None
60
"""
61
```
62
63
Usage examples:
64
65
```python
66
from beartype.claw import beartype_package
67
68
# Decorate specific package
69
beartype_package("requests")
70
beartype_package("numpy")
71
72
# With configuration
73
beartype_package("pandas", conf=BeartypeConf(strategy=BeartypeStrategy.O1))
74
75
# Import happens after decoration setup
76
import requests # All annotated functions in requests are type-checked
77
```
78
79
### Multiple Package Decoration
80
81
Apply beartype to multiple specific packages at once.
82
83
```python { .api }
84
def beartype_packages(*package_names, conf=None):
85
"""
86
Apply beartype to multiple packages by name.
87
88
Parameters:
89
- *package_names: str - Names of packages to decorate
90
- conf: BeartypeConf - Optional configuration
91
92
Returns:
93
None
94
"""
95
```
96
97
Usage examples:
98
99
```python
100
from beartype.claw import beartype_packages
101
102
# Decorate multiple packages
103
beartype_packages("requests", "urllib3", "httpx")
104
105
# With configuration
106
beartype_packages(
107
"numpy", "pandas", "scipy",
108
conf=BeartypeConf(strategy=BeartypeStrategy.Ologn)
109
)
110
```
111
112
### Current Package Decoration
113
114
Apply beartype to the calling package automatically.
115
116
```python { .api }
117
def beartype_this_package(conf=None):
118
"""
119
Apply beartype to the package from which this function is called.
120
121
Automatically decorates all annotated functions in the calling package.
122
Typically called from a package's __init__.py file.
123
124
Parameters:
125
- conf: BeartypeConf - Optional configuration
126
127
Returns:
128
None
129
"""
130
```
131
132
Usage examples:
133
134
```python
135
# In your package's __init__.py file:
136
from beartype.claw import beartype_this_package
137
138
# Apply beartype to all modules in current package
139
beartype_this_package()
140
141
# With custom configuration
142
beartype_this_package(conf=BeartypeConf(
143
strategy=BeartypeStrategy.On,
144
is_debug=True
145
))
146
147
# All annotated functions in this package are now type-checked
148
def my_function(x: int) -> str:
149
return str(x) # Automatically type-checked
150
```
151
152
### Context Manager
153
154
Temporarily apply beartype within a specific scope using a context manager.
155
156
```python { .api }
157
class beartyping:
158
"""
159
Context manager for temporary beartype application.
160
161
Applies beartype configuration within the context and restores
162
previous state upon exit.
163
"""
164
165
def __init__(self, conf=None):
166
"""
167
Initialize context manager.
168
169
Parameters:
170
- conf: BeartypeConf - Optional configuration
171
"""
172
173
def __enter__(self):
174
"""Enter context with beartype active."""
175
176
def __exit__(self, exc_type, exc_val, exc_tb):
177
"""Exit context and restore previous state."""
178
```
179
180
Usage examples:
181
182
```python
183
from beartype.claw import beartyping
184
from beartype import BeartypeConf, BeartypeStrategy
185
186
# Temporary beartype application
187
with beartyping():
188
import some_module # Type-checked within this scope
189
190
# Type checking no longer applied to new imports
191
192
# With custom configuration
193
with beartyping(conf=BeartypeConf(strategy=BeartypeStrategy.On)):
194
import another_module # Thoroughly type-checked
195
196
def temp_function(x: int) -> int:
197
return x * 2 # Type-checked within context
198
```
199
200
### Advanced Usage Patterns
201
202
Combining different import hook approaches for fine-grained control:
203
204
```python
205
from beartype.claw import beartype_all, beartype_package
206
from beartype import BeartypeConf, BeartypeStrategy
207
208
# Different strategies for different packages
209
beartype_package("critical_package", conf=BeartypeConf(
210
strategy=BeartypeStrategy.On, # Thorough checking
211
is_debug=True
212
))
213
214
beartype_package("performance_package", conf=BeartypeConf(
215
strategy=BeartypeStrategy.O1 # Fast checking
216
))
217
218
# Catch-all for remaining packages
219
beartype_all(conf=BeartypeConf(
220
strategy=BeartypeStrategy.Ologn, # Balanced approach
221
violation_type=UserWarning # Warnings instead of errors
222
))
223
```
224
225
### Configuration Integration
226
227
All import hook functions accept `BeartypeConf` objects for customization:
228
229
```python
230
from beartype.claw import beartype_this_package
231
from beartype import BeartypeConf, BeartypeStrategy
232
233
# Performance-optimized configuration
234
fast_conf = BeartypeConf(
235
strategy=BeartypeStrategy.O1,
236
is_debug=False
237
)
238
239
# Development configuration with thorough checking
240
dev_conf = BeartypeConf(
241
strategy=BeartypeStrategy.On,
242
is_debug=True,
243
is_color=True
244
)
245
246
# Production configuration with warning-based violations
247
prod_conf = BeartypeConf(
248
strategy=BeartypeStrategy.Ologn,
249
violation_type=UserWarning
250
)
251
252
# Apply based on environment
253
import os
254
if os.getenv("ENV") == "development":
255
beartype_this_package(conf=dev_conf)
256
elif os.getenv("ENV") == "production":
257
beartype_this_package(conf=prod_conf)
258
else:
259
beartype_this_package(conf=fast_conf)
260
```
261
262
### Best Practices
263
264
1. **Call Early**: Import hook functions should be called as early as possible, preferably in your package's `__init__.py`
265
266
2. **Before Imports**: Set up import hooks before importing the packages you want to decorate
267
268
3. **Configuration Consistency**: Use consistent `BeartypeConf` objects across related packages
269
270
4. **Environment Awareness**: Consider different configurations for development vs. production environments
271
272
5. **Performance Monitoring**: Use appropriate strategies based on performance requirements