0
# Type System
1
2
Comprehensive type representations used by mypy's static analysis engine. This system implements Python's complete type system including generics, unions, protocols, and advanced typing features.
3
4
## Capabilities
5
6
### Base Type Classes
7
8
Foundation classes that form the hierarchy for all type representations.
9
10
```python { .api }
11
class Type:
12
"""
13
Abstract base class for all type representations in mypy.
14
15
All types inherit from this class and implement the visitor pattern
16
for type operations and transformations.
17
"""
18
19
class ProperType(Type):
20
"""
21
Base class for concrete type representations.
22
23
Inherits from Type and represents fully resolved types that are
24
not type aliases or other indirection types.
25
"""
26
```
27
28
### Concrete Type Classes
29
30
Core type representations for Python's type system.
31
32
```python { .api }
33
class AnyType(ProperType):
34
"""
35
Represents the Any type - the top type in Python's type system.
36
37
Any is compatible with all other types in both directions.
38
Used when type information is unknown or when opting out of type checking.
39
40
Attributes:
41
- type_of_any: int - Reason for Any (missing annotation, error, etc.)
42
"""
43
44
class NoneType(ProperType):
45
"""
46
Represents the type of None value.
47
48
In Python's type system, None has its own special type.
49
Often used in Optional[T] which is equivalent to Union[T, None].
50
"""
51
52
class UninhabitedType(ProperType):
53
"""
54
Represents the bottom type (Never) - a type with no possible values.
55
56
Used for functions that never return (always raise exceptions)
57
and for unreachable code paths.
58
"""
59
60
class Instance(ProperType):
61
"""
62
Represents instances of classes and built-in types.
63
64
This is the most common type representation, covering class instances,
65
built-in types like int/str/list, and generic instantiations like List[int].
66
67
Attributes:
68
- type: TypeInfo - Information about the class
69
- args: list[Type] - Type arguments for generic types
70
- erased: bool - Whether type arguments were erased
71
"""
72
73
class CallableType(ProperType):
74
"""
75
Represents function and method types with complete call signatures.
76
77
Includes parameter types, return type, and calling conventions.
78
Supports overloads, keyword-only parameters, and varargs.
79
80
Attributes:
81
- arg_types: list[Type] - Parameter types
82
- return_type: Type - Return type
83
- arg_names: list[str | None] - Parameter names
84
- arg_kinds: list[int] - Parameter kinds (positional, keyword, etc.)
85
- variables: list[TypeVarLikeType] - Type variables in scope
86
- is_ellipsis: bool - Whether this is Callable[..., RetType]
87
"""
88
89
class TupleType(ProperType):
90
"""
91
Represents tuple types with known element types.
92
93
Supports both fixed-length tuples like Tuple[int, str] and
94
variable-length tuples like Tuple[int, ...].
95
96
Attributes:
97
- items: list[Type] - Element types
98
- partial_fallback: Instance - Fallback to tuple[Any, ...]
99
"""
100
101
class UnionType(ProperType):
102
"""
103
Represents union types (X | Y or Union[X, Y]).
104
105
A type that can be one of several alternatives.
106
Mypy automatically simplifies unions and removes duplicates.
107
108
Attributes:
109
- items: list[Type] - Union member types
110
"""
111
112
class TypedDictType(ProperType):
113
"""
114
Represents TypedDict types - structured dictionary types.
115
116
Defines dictionaries with specific required and optional keys
117
and their corresponding value types.
118
119
Attributes:
120
- items: dict[str, Type] - Required key-value types
121
- required_keys: set[str] - Required keys
122
- fallback: Instance - Fallback to dict type
123
"""
124
125
class LiteralType(ProperType):
126
"""
127
Represents literal value types (Literal['value']).
128
129
Types restricted to specific literal values, enabling
130
fine-grained type checking based on actual values.
131
132
Attributes:
133
- value: Any - The literal value
134
- fallback: Instance - Fallback type for the value
135
"""
136
137
class TypeType(ProperType):
138
"""
139
Represents Type[X] types - the type of type objects.
140
141
Used for metaclass typing and when working with class objects
142
rather than instances of classes.
143
144
Attributes:
145
- item: Type - The type being referenced
146
"""
147
```
148
149
### Type Variable Classes
150
151
Support for generic programming with type variables.
152
153
```python { .api }
154
class TypeVarType(Type):
155
"""
156
Represents type variables (T, K, V, etc.) for generic programming.
157
158
Type variables are placeholders that can be bound to specific types
159
when generic functions or classes are instantiated.
160
161
Attributes:
162
- name: str - Type variable name
163
- id: TypeVarId - Unique identifier
164
- values: list[Type] - Allowed values (for constrained type vars)
165
- upper_bound: Type - Upper bound constraint
166
- variance: int - Variance (covariant, contravariant, invariant)
167
"""
168
169
class ParamSpecType(Type):
170
"""
171
Represents parameter specification variables (ParamSpec).
172
173
Used to preserve callable signatures in higher-order functions
174
and generic callable types.
175
176
Attributes:
177
- name: str - ParamSpec name
178
- id: TypeVarId - Unique identifier
179
- upper_bound: Type - Upper bound (usually Callable)
180
"""
181
182
class TypeVarTupleType(Type):
183
"""
184
Represents variadic type variables (TypeVarTuple).
185
186
Used for variable-length generic type parameters,
187
enabling generic types with arbitrary numbers of type arguments.
188
189
Attributes:
190
- name: str - TypeVarTuple name
191
- id: TypeVarId - Unique identifier
192
- upper_bound: Type - Upper bound constraint
193
"""
194
```
195
196
### Intermediate and Special Types
197
198
Types used during analysis and for special purposes.
199
200
```python { .api }
201
class TypeAliasType(Type):
202
"""
203
Type alias to another type - supports recursive type aliases.
204
205
Represents user-defined type aliases that can reference themselves
206
for recursive data structures.
207
208
Attributes:
209
- alias: TypeAlias - The type alias definition
210
- args: list[Type] - Type arguments for generic aliases
211
"""
212
213
class UnboundType(ProperType):
214
"""
215
Instance type that has not been bound during semantic analysis.
216
217
Used during the early phases of type checking before names
218
are resolved to their actual type definitions.
219
220
Attributes:
221
- name: str - The unresolved type name
222
- args: list[Type] - Type arguments if present
223
"""
224
225
class UnpackType(ProperType):
226
"""
227
Type operator Unpack from PEP646 for TypeVarTuple unpacking.
228
229
Used for unpacking TypeVarTuple in generic types, enabling
230
variable-length generic parameter lists.
231
232
Attributes:
233
- type: Type - The type being unpacked
234
"""
235
236
class PartialType(ProperType):
237
"""
238
Type with unknown type arguments during inference.
239
240
Used for types like List[?] during multiphase initialization
241
where type arguments are inferred later.
242
243
Attributes:
244
- type: Type | None - Partial type information
245
- var: Var | None - Associated variable
246
"""
247
248
class ErasedType(ProperType):
249
"""
250
Placeholder for an erased type during type inference.
251
252
Used internally when type information has been erased
253
during generic type processing.
254
"""
255
256
class DeletedType(ProperType):
257
"""
258
Type of deleted variables.
259
260
Variables with this type can be used as lvalues (assignment targets)
261
but not as rvalues (in expressions).
262
"""
263
264
class EllipsisType(ProperType):
265
"""
266
The type of ... (ellipsis) literal.
267
268
Used in Callable[..., ReturnType] and other contexts where
269
ellipsis has special meaning.
270
"""
271
272
class PlaceholderType(ProperType):
273
"""
274
Temporary, yet-unknown type during semantic analysis.
275
276
Used when there's a forward reference to a type before
277
the actual type definition is encountered.
278
279
Attributes:
280
- fullname: str - Full name of the referenced type
281
- args: list[Type] - Type arguments if present
282
"""
283
284
class RawExpressionType(ProperType):
285
"""
286
Synthetic type representing arbitrary expressions.
287
288
Used for expressions that don't cleanly translate into
289
a specific type representation.
290
291
Attributes:
292
- literal_value: Any - The raw expression value
293
"""
294
```
295
296
### Advanced Type Features
297
298
Types supporting modern Python typing features.
299
300
```python { .api }
301
class RequiredType(Type):
302
"""
303
Required[T] or NotRequired[T] for TypedDict fields.
304
305
Used to mark TypedDict fields as required or not required,
306
overriding the default requirement status.
307
308
Attributes:
309
- item: Type - The field type
310
- required: bool - Whether the field is required
311
"""
312
313
class ReadOnlyType(Type):
314
"""
315
ReadOnly[T] for TypedDict fields.
316
317
Marks TypedDict fields as read-only, preventing modification
318
after initialization.
319
320
Attributes:
321
- item: Type - The field type
322
"""
323
324
class TypeGuardedType(Type):
325
"""
326
Type used internally for isinstance checks and type guards.
327
328
Used by mypy's type narrowing system to track types that have
329
been confirmed through runtime type checks.
330
331
Attributes:
332
- type_guard: Type - The guarded type
333
"""
334
```
335
336
## Type Operations
337
338
### Type Construction
339
340
```python
341
from mypy.types import Instance, CallableType, UnionType, TypeVarType
342
from mypy.nodes import TypeInfo
343
344
# Create instance type
345
int_type = Instance(int_typeinfo, [], line=-1)
346
str_type = Instance(str_typeinfo, [], line=-1)
347
348
# Create callable type
349
def_type = CallableType(
350
arg_types=[str_type], # Parameter types
351
arg_kinds=[ARG_POS], # Parameter kinds
352
arg_names=['name'], # Parameter names
353
return_type=str_type, # Return type
354
fallback=function_type # Fallback type
355
)
356
357
# Create union type
358
optional_str = UnionType([str_type, none_type])
359
360
# Create generic type with type variables
361
T = TypeVarType('T', 'T', -1, [], object_type)
362
generic_list = Instance(list_typeinfo, [T], line=-1)
363
```
364
365
### Type Checking Operations
366
367
```python
368
from mypy.subtypes import is_subtype
369
from mypy.typeops import make_simplified_union
370
from mypy.meet import meet_types
371
from mypy.join import join_types
372
373
# Subtype checking
374
if is_subtype(child_type, parent_type):
375
print("child_type is a subtype of parent_type")
376
377
# Type joins (least upper bound)
378
common_type = join_types(type1, type2)
379
380
# Type meets (greatest lower bound)
381
narrow_type = meet_types(type1, type2)
382
383
# Union simplification
384
simplified = make_simplified_union([int_type, str_type, int_type])
385
```
386
387
### Type Visitor Pattern
388
389
```python
390
from mypy.visitor import TypeVisitor
391
392
class TypeCollector(TypeVisitor[list[Type]]):
393
"""Collect all types in a type expression."""
394
395
def visit_instance(self, t: Instance) -> list[Type]:
396
result = [t]
397
for arg in t.args:
398
result.extend(arg.accept(self))
399
return result
400
401
def visit_callable_type(self, t: CallableType) -> list[Type]:
402
result = [t]
403
for arg_type in t.arg_types:
404
result.extend(arg_type.accept(self))
405
result.extend(t.return_type.accept(self))
406
return result
407
408
def visit_union_type(self, t: UnionType) -> list[Type]:
409
result = [t]
410
for item in t.items:
411
result.extend(item.accept(self))
412
return result
413
414
# Usage
415
collector = TypeCollector()
416
all_types = some_type.accept(collector)
417
```
418
419
## Advanced Type System Features
420
421
### Generic Types
422
423
```python
424
from mypy.types import Instance, TypeVarType
425
426
# Type variable definition
427
T = TypeVarType('T', 'T', -1, [], object_type)
428
K = TypeVarType('K', 'K', -1, [], object_type)
429
V = TypeVarType('V', 'V', -1, [], object_type)
430
431
# Generic class instantiation
432
list_of_int = Instance(list_typeinfo, [int_type], line=-1)
433
dict_str_int = Instance(dict_typeinfo, [str_type, int_type], line=-1)
434
435
# Constrained type variables
436
AnyStr = TypeVarType(
437
'AnyStr', 'AnyStr', -1,
438
values=[str_type, bytes_type], # Constrained to str or bytes
439
upper_bound=object_type
440
)
441
```
442
443
### Protocol Types
444
445
```python
446
from mypy.types import Instance
447
from mypy.nodes import TypeInfo
448
449
# Protocol definition (structural typing)
450
class ProtocolType(Instance):
451
"""
452
Represents protocol types for structural subtyping.
453
454
Protocols define interfaces based on structure rather than
455
explicit inheritance, enabling duck typing with static checking.
456
"""
457
458
def __init__(self, typeinfo: TypeInfo, args: list[Type]):
459
super().__init__(typeinfo, args, line=-1)
460
self.protocol = True
461
462
# Usage example
463
iterable_protocol = ProtocolType(iterable_typeinfo, [T])
464
```
465
466
### Callable Overloads
467
468
```python
469
from mypy.types import CallableType, Overloaded
470
471
# Multiple callable signatures
472
overload1 = CallableType([int_type], str_type, ...)
473
overload2 = CallableType([str_type], str_type, ...)
474
475
# Overloaded function type
476
overloaded_func = Overloaded([overload1, overload2])
477
```
478
479
## Type Analysis Integration
480
481
### Working with AST Nodes
482
483
```python
484
from mypy.nodes import FuncDef, ClassDef
485
from mypy.types import CallableType, Instance
486
487
def analyze_function(funcdef: FuncDef) -> CallableType:
488
"""Analyze function definition and create callable type."""
489
arg_types = []
490
arg_names = []
491
arg_kinds = []
492
493
for arg in funcdef.arguments:
494
if arg.type_annotation:
495
arg_types.append(analyze_type(arg.type_annotation))
496
else:
497
arg_types.append(AnyType(TypeOfAny.unannotated))
498
499
arg_names.append(arg.variable.name)
500
arg_kinds.append(arg.kind)
501
502
return_type = analyze_type(funcdef.type) if funcdef.type else AnyType(TypeOfAny.unannotated)
503
504
return CallableType(
505
arg_types=arg_types,
506
arg_kinds=arg_kinds,
507
arg_names=arg_names,
508
return_type=return_type,
509
fallback=function_type
510
)
511
```
512
513
### Type Inference
514
515
```python
516
from mypy.constraints import infer_constraints
517
from mypy.solve import solve_constraints
518
519
def infer_type_arguments(callable: CallableType, arg_types: list[Type]) -> list[Type]:
520
"""Infer type arguments for generic function call."""
521
constraints = []
522
523
# Collect constraints from arguments
524
for formal, actual in zip(callable.arg_types, arg_types):
525
constraints.extend(infer_constraints(formal, actual, SUPERTYPE_OF))
526
527
# Solve constraints to get type variable bindings
528
solution = solve_constraints(callable.variables, constraints)
529
530
return [solution.get(tv.id, AnyType(TypeOfAny.from_error))
531
for tv in callable.variables]
532
```
533
534
## Type System Constants
535
536
### Type Kinds and Flags
537
538
```python
539
# Type variable variance
540
COVARIANT = 1
541
CONTRAVARIANT = -1
542
INVARIANT = 0
543
544
# Argument kinds
545
ARG_POS = 0 # Positional argument
546
ARG_OPT = 1 # Optional argument (with default)
547
ARG_STAR = 2 # *args
548
ARG_STAR2 = 3 # **kwargs
549
550
# Type sources
551
TypeOfAny.from_error # Any from type error
552
TypeOfAny.unannotated # Missing annotation
553
TypeOfAny.explicit # Explicit Any annotation
554
TypeOfAny.from_omitted_generics # Unparameterized generic
555
```
556
557
### Built-in Type Names
558
559
```python
560
# Common type name constants
561
TUPLE_NAMES = ('builtins.tuple', 'tuple')
562
LIST_NAMES = ('builtins.list', 'list')
563
DICT_NAMES = ('builtins.dict', 'dict')
564
SET_NAMES = ('builtins.set', 'set')
565
CALLABLE_NAMES = ('builtins.function', 'typing.Callable')
566
PROTOCOL_NAMES = ('typing.Protocol', 'typing_extensions.Protocol')
567
```