0
# Object-Oriented API (DOOR)
1
2
DOOR (Decidedly Object-Oriented Runtime-checking) API provides advanced type hint manipulation and introspection capabilities. This object-oriented interface wraps the standard typing module with enhanced functionality for runtime type checking and validation.
3
4
## Capabilities
5
6
### Base Type Hint Class
7
8
Abstract base class for all type hint objects providing common interface.
9
10
```python { .api }
11
class TypeHint:
12
"""
13
Abstract base class for type hint introspection objects.
14
15
Provides object-oriented interface to type hints with enhanced
16
runtime capabilities beyond standard typing module.
17
"""
18
19
def __init__(self, hint):
20
"""Initialize with a type hint object."""
21
22
def __eq__(self, other):
23
"""Test equality with another type hint."""
24
25
def __hash__(self):
26
"""Compute hash for use in sets and dicts."""
27
28
def __repr__(self):
29
"""Return string representation."""
30
```
31
32
### Specific Type Hint Classes
33
34
#### Union and Optional Types
35
36
```python { .api }
37
class UnionTypeHint(TypeHint):
38
"""
39
Type hint for Union types (PEP 484/604).
40
41
Represents typing.Union type hints including Optional[T] which
42
is equivalent to Union[T, None].
43
"""
44
45
@property
46
def args(self):
47
"""Tuple of union member types."""
48
49
@property
50
def is_optional(self):
51
"""True if this union includes None (i.e., Optional)."""
52
```
53
54
#### Annotated Types
55
56
```python { .api }
57
class AnnotatedTypeHint(TypeHint):
58
"""
59
Type hint for Annotated types (PEP 593).
60
61
Represents typing.Annotated type hints with metadata.
62
"""
63
64
@property
65
def origin(self):
66
"""The base type being annotated."""
67
68
@property
69
def metadata(self):
70
"""Tuple of annotation metadata objects."""
71
```
72
73
#### Callable Types
74
75
```python { .api }
76
class CallableTypeHint(TypeHint):
77
"""
78
Type hint for Callable types.
79
80
Represents typing.Callable type hints with parameter and return types.
81
"""
82
83
@property
84
def args(self):
85
"""List of parameter types or Ellipsis for any parameters."""
86
87
@property
88
def return_type(self):
89
"""Return type of the callable."""
90
```
91
92
#### Generic and Subscripted Types
93
94
```python { .api }
95
class GenericTypeHint(TypeHint):
96
"""
97
Type hint for Generic types.
98
99
Represents typing.Generic base classes and their subclasses.
100
"""
101
102
@property
103
def type_vars(self):
104
"""Tuple of TypeVar objects used by this generic."""
105
106
class SubscriptedTypeHint(TypeHint):
107
"""
108
Type hint for subscripted generic types.
109
110
Represents generic types with concrete type arguments (e.g., List[int]).
111
"""
112
113
@property
114
def origin(self):
115
"""The generic base type (e.g., list for List[int])."""
116
117
@property
118
def args(self):
119
"""Tuple of type arguments (e.g., (int,) for List[int])."""
120
```
121
122
#### Tuple Types
123
124
```python { .api }
125
class TupleFixedTypeHint(TypeHint):
126
"""
127
Type hint for fixed-length tuple types.
128
129
Represents tuple type hints with specific element types.
130
"""
131
132
@property
133
def item_types(self):
134
"""Tuple of element types in order."""
135
136
class TupleVariableTypeHint(TypeHint):
137
"""
138
Type hint for variable-length tuple types.
139
140
Represents tuple type hints with repeated element type.
141
"""
142
143
@property
144
def item_type(self):
145
"""Type of tuple elements."""
146
```
147
148
#### Special Types
149
150
```python { .api }
151
class AnyTypeHint(TypeHint):
152
"""Type hint for typing.Any."""
153
154
class ClassTypeHint(TypeHint):
155
"""Type hint for class-based types."""
156
157
@property
158
def cls(self):
159
"""The class object this hint represents."""
160
161
class LiteralTypeHint(TypeHint):
162
"""
163
Type hint for Literal types (PEP 586).
164
165
Represents typing.Literal type hints with specific values.
166
"""
167
168
@property
169
def values(self):
170
"""Tuple of literal values."""
171
172
class NewTypeTypeHint(TypeHint):
173
"""
174
Type hint for NewType types.
175
176
Represents typing.NewType derived types.
177
"""
178
179
@property
180
def name(self):
181
"""Name of the new type."""
182
183
@property
184
def supertype(self):
185
"""Base type that this NewType extends."""
186
187
class TypeVarTypeHint(TypeHint):
188
"""
189
Type hint for TypeVar types.
190
191
Represents typing.TypeVar type variables.
192
"""
193
194
@property
195
def name(self):
196
"""Name of the type variable."""
197
198
@property
199
def bound(self):
200
"""Upper bound type or None."""
201
202
@property
203
def constraints(self):
204
"""Tuple of allowed types or empty tuple."""
205
```
206
207
### Validation Functions
208
209
Runtime type checking and validation utilities.
210
211
```python { .api }
212
def is_bearable(obj, hint):
213
"""
214
Test whether an object satisfies a type hint.
215
216
Parameters:
217
- obj: Any - Object to test
218
- hint: Any - Type hint to test against
219
220
Returns:
221
bool - True if object satisfies hint, False otherwise
222
"""
223
224
def die_if_unbearable(obj, hint, exc_cls=BeartypeDoorHintViolation):
225
"""
226
Raise exception if object doesn't satisfy type hint.
227
228
Parameters:
229
- obj: Any - Object to test
230
- hint: Any - Type hint to test against
231
- exc_cls: type - Exception class to raise on failure
232
233
Returns:
234
None - Returns normally if object satisfies hint
235
236
Raises:
237
BeartypeDoorHintViolation - If object doesn't satisfy hint
238
"""
239
240
def is_subhint(subhint, superhint):
241
"""
242
Test whether one type hint is a subtype of another.
243
244
Parameters:
245
- subhint: Any - Potential subtype hint
246
- superhint: Any - Potential supertype hint
247
248
Returns:
249
bool - True if subhint is subtype of superhint
250
"""
251
```
252
253
### Type Inference
254
255
Automatic type hint inference from runtime objects.
256
257
```python { .api }
258
def infer_hint(obj):
259
"""
260
Infer type hint from a runtime object.
261
262
Analyzes an object and returns the most specific type hint
263
that describes it.
264
265
Parameters:
266
- obj: Any - Object to infer type hint for
267
268
Returns:
269
Any - Inferred type hint
270
"""
271
```
272
273
### Usage Examples
274
275
#### Basic Type Checking
276
277
```python
278
from beartype.door import is_bearable, die_if_unbearable
279
from typing import List, Optional
280
281
# Test type compatibility
282
data = [1, 2, 3]
283
print(is_bearable(data, List[int])) # True
284
print(is_bearable(data, List[str])) # False
285
286
# Raise exception on type mismatch
287
value: Optional[str] = "hello"
288
die_if_unbearable(value, Optional[str]) # OK
289
290
try:
291
die_if_unbearable(42, Optional[str]) # Raises exception
292
except BeartypeDoorHintViolation as e:
293
print(f"Type violation: {e}")
294
```
295
296
#### Type Hint Introspection
297
298
```python
299
from beartype.door import TypeHint, UnionTypeHint, AnnotatedTypeHint
300
from typing import Union, Optional, Annotated
301
302
# Introspect Union types
303
hint = TypeHint(Optional[str])
304
if isinstance(hint, UnionTypeHint):
305
print(f"Union args: {hint.args}") # (str, NoneType)
306
print(f"Is optional: {hint.is_optional}") # True
307
308
# Introspect Annotated types
309
from beartype.vale import Is
310
311
annotated_hint = TypeHint(Annotated[int, Is[lambda x: x > 0]])
312
if isinstance(annotated_hint, AnnotatedTypeHint):
313
print(f"Base type: {annotated_hint.origin}") # int
314
print(f"Metadata: {annotated_hint.metadata}") # (validator,)
315
```
316
317
#### Type Inference
318
319
```python
320
from beartype.door import infer_hint
321
322
# Infer from simple objects
323
print(infer_hint(42)) # int
324
print(infer_hint("hello")) # str
325
print(infer_hint([1, 2, 3])) # List[int]
326
327
# Infer from complex structures
328
data = {"name": "Alice", "age": 30, "scores": [95, 87, 92]}
329
hint = infer_hint(data)
330
print(hint) # Dict[str, Union[str, int, List[int]]]
331
```
332
333
#### Subtype Checking
334
335
```python
336
from beartype.door import is_subhint
337
from typing import List, Sequence, Union
338
339
# Check type relationships
340
print(is_subhint(List[int], Sequence[int])) # True
341
print(is_subhint(int, Union[int, str])) # True
342
print(is_subhint(Union[int, str], int)) # False
343
```