Types and type inference
How Python annotations map to CLR types, what the compiler infers without annotations, and what happens where no static type can be found.
Static types are the basis of Typhon’s speed and of its interoperability with C#. Typhon takes them from annotations where they exist and infers them for the whole program where they do not. Where neither works, the compiler falls back to .NET’s dynamic, and the project’s type mode decides whether that is allowed.
Annotations and CLR types
| Python annotation | CLR type |
|---|---|
int | long (System.Int64), or BigInteger in big-int mode |
float | double |
str | string |
bool | bool |
None as a return type | void |
list[T] | List<T> |
dict[K, V] | Dictionary<K, V> |
set[T] | HashSet<T> |
tuple[A, B] | (A, B) (ValueTuple) |
Optional[T], T | None | T? |
Callable[[A], R] | Func<A, R> or Action<A> |
Iterator[T] | IEnumerable<T> |
Array[T] (Typhon) | T[] |
decimal, int32, float32 and other sized types | decimal, int, float and the other CLR types |
Any | dynamic |
| any .NET type | the type itself |
Union types other than X | None compile to object in the current version.
Local variables
The compiler declares local variables with var and lets C# infer their type, so x = 1.5 becomes var x = 1.5. Python locals belong to the whole function while C# locals belong to a block. The compiler therefore places each declaration in the innermost block that contains all uses of the variable, and it hoists the declaration where that is not possible.
Whole-program type inference
Parameters, return types and fields without annotations are inferred from the whole program.
- Parameters come from call sites. Every call of a project function or constructor records the argument types. Each distinct combination becomes one typed overload, so
scale(3, 2)andscale(1.5, 2.0)call separatelonganddoubleversions and keep Python’s behaviour forintandfloat. - Return types come from
returnstatements, recursion included. A function that returns anintorNonegets the return typelong?. - Fields come from the constructor.
self.x = xgives the field the type thatxhas in every constructor signature.
The following program has no annotations:
def scale(value, factor):
return value * factor
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(scale(3, 2), scale(1.5, 2.0), fib(20))
typhon emit shows these signatures in the generated C#:
public static long scale(long value, long factor)
public static double scale(double value, double factor)
public static long fib(long n)
The program prints 6 3.0 6765 under Typhon and under CPython.
Containers that start out empty get their type from later use. [None] * n and [None for _ in ...] take the type of what the program stores in them later, and so do module-level lists such as NAMES = [] that are filled anywhere in the module. A lambda stored in a variable becomes a delegate typed by its calls.
Inference repeats until the signatures stop changing. If they do not settle, the code is emitted as written. An untyped dynamic version of a function remains only where a call passes a value of unknown type. A function passed as a value, as in map(f, xs), is called through a lambda and keeps its untyped version as well.
Method parameters are inferred the same way, from the calls whose receiver’s class is known, such as obj.m(x) and self.m(x). Each call signature gets an overload, and a late-bound version remains for calls the compiler cannot see, such as calls through getattr. Methods that override or are overridden, decorated methods, methods of generic classes and methods a Protocol declares are not inferred.
The conformance case tests/conformance/cases/untyped.ty contains no annotations at all and compiles in strict mode.
Dynamic values and type modes
Some values have no static type the compiler can determine: an empty list whose element type no code reveals, a value from a dynamic API, or a parameter of a function that only C# calls. The compiler then falls back to C# dynamic. The type mode decides how it treats each such place:
| Mode | Implicit dynamic | Suited for |
|---|---|---|
strict | Compile error TY1001 | Libraries, hot paths, and code that is to be compiled with Native AOT |
warn (default) | Compiles, with one warning per place | Everyday code and gradual migration |
permissive | Compiles without a warning | Porting existing Python code |
The mode is set per project with TyphonTypeMode or per run with typhon run --strict and --permissive. An explicit Any annotation is allowed in every mode.
dynamic is slow. Before whole-program inference existed, the N-body benchmark without annotations fell back to dynamic and took 2,168 ms, against 40.3 ms for the annotated version. With inference, both versions run at about the same speed: 74 and 72 times faster than CPython in the same run. Native AOT cannot run late-bound code at all, so typhon build --aot also rejects dynamic values that come from libraries (TY2001).