Skip to content
Jukka Lehtosalo edited this page Mar 30, 2016 · 1 revision

The mypy type checker checks if a program has type errors and infers the types of variables and expressions. It is immplemented as an AST visitor.

The checker.TypeChecker class (in mypy/checker.py) takes as an input a semantically analyzed file AST (instance of nodes.MypyFile). It binds attribute references in the AST and generates a map from AST nodes to types (the type_map attribute).

TODO describe type operations

Type inference

Each subexpression AST node is assigned an inferred type. For example, for expression

  foo(bar, x.y) 

the type checker will infer types for 4 subexpressions: foo, bar, x, x.y and foo(bar, x.y).

Attribute expressions with 'any' receiver types are special, and cannot be bound during type checking. Instead, the type of expression x.y is just 'any' if the type of x is 'any'.

TODO: describe type inference of generic types

Type checking with Any types

Type compatibility in mypy is different from languages such as Java. The Any type is compatible with every other type, and vice versa. This is in addition to normal nominal subtyping, which is similar to Java (but primitive types are not special).

Examples:

  • int is compatible with Any
  • List[int] is compatible with List[Any]
  • List[int] is compatible with Sequence[Any] (subtyping + any types)