Experiment · proof of concept
Python syntax, compiled to .NET
Typhon is an experimental compiler for type-annotated Python. It produces ordinary .NET IL, so C# code can call what Typhon compiles, and Typhon code can import any .NET namespace. The project is an experiment, and most of its code is generated by AI.
from dataclasses import dataclass
import math
@dataclass
class Point:
x: float
y: float
def path_length(points: list[Point]) -> float:
total = 0.0
for a, b in zip(points, points[1:]):
total += math.hypot(b.x - a.x, b.y - a.y)
return total
route = [Point(0, 0), Point(3, 4), Point(6, 8)]
print(f"{len(route)} points, length {path_length(route):.1f}") This file runs unchanged under CPython and under typhon run. Both print 3 points, length 10.0.
Most of Typhon's code is generated by AI, based on a small set of core principles and ideas: valid Python syntax, static types, C# and Roslyn as the back end, and Python protocols mapped to .NET. A test harness checks the compiled programs against CPython, using existing programs and libraries. Typhon is still an experiment. Expect missing features and bugs, and no stability or support promises.
Principles, status and roadmapCompilation through C# and Roslyn
The Typhon compiler parses the Python source, resolves names and types against the .NET libraries a project references, and writes C#. Roslyn, the C# compiler, turns that C# into IL. #line directives map every error, warning, stack trace line and breakpoint back to the .ty file.
- .ty source Python 3.12 syntax with type annotations
- Lexer and parser Hand-written, with INDENT and DEDENT tokens
- Analysis Scopes, names and types resolved against Roslyn symbols; whole-program type inference
- C# with #line Generated source that maps back to the .ty file
- Roslyn The same compilation as the project's own .cs files
- IL In a .dll or .exe; Native AOT compiles it further into a native executable
.ty file to IL. Roslyn compiles the generated C# together with the project's C# code. public partial class Point
{
public double x { get; set; }
public double y { get; set; }
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
// ToString, Equals, == and GetHashCode come from @dataclass
}
public static double path_length(List<Point> points)
{
checked
{
var total = 0.0;
foreach (var (a, b) in zip(points, slice(points, 1, null)))
{
total += math.hypot((b.x - a.x), (b.y - a.y));
}
return total;
}
} Abridged output of typhon emit route.ty for the class and the function above, without the #line directives. Type annotations became CLR types: float is double, list[Point] is List<Point>.
First measurements
The repository contains a benchmark suite and a conformance suite. The figures below are taken from their published results. They describe small programs on a single machine. How larger applications behave has not been measured.
| Result | Measurement | Context |
|---|---|---|
| 11.1x | Geometric mean speed-up over CPython | Nine typed pure-Python programs, compiled with the JIT build. Individual programs range from 1.9x to 75x. As Native AOT executables the mean is 13.6x. |
| 654 of 656 | Conformance cases that match CPython | A case passes when Typhon prints byte for byte what CPython 3.15 prints. The figure covers typhon run. In the last Native AOT pass, 10 of the then 17 cases matched. |
| 1.5 to 1.9 MB | Self-contained Native AOT executable | A small program needs 9 MB of RAM on Windows, where CPython needs 12 MB. On Linux it starts in 1.8 ms. |
| 1.04x | NumPy programs against NumPy | Typhon runs NumPy code against its own C# library. The figure is the geometric mean over six programs with the JIT build, and Native AOT reaches 1.13x. In these runs, NumPy was faster at matrix multiplication and dense linear algebra, a gap that a later rewrite of Typhon.NumPy narrowed. |
Measured on one laptop (Intel Core Ultra 9 285HX) with .NET 11.0.100, CPython 3.15.2 and NumPy 2.5.5. The benchmark programs have between 10 and 85 lines of code each. Compile time is excluded from the speed-ups.
Benchmark results and methodTyphon and C# in one assembly
A Roslyn source generator compiles .ty files inside an ordinary .csproj. Typhon classes become CLR classes, so C# can construct them, call them and derive from them. In the other direction, Typhon code implements C# interfaces and uses C# types from the same project. The repository also contains samples written in Typhon: a minimal API on ASP.NET Core, Blazor apps on the server and in the browser, a browser app on .NET WebAssembly, desktop apps for Windows Forms, WPF and WinUI 3, a playground that compiles and runs Typhon in the browser, and a Godot project with GDScript compiled by Typhon.
from CSharpApp import TaxRules, IDiscount
from dataclasses import dataclass
class StudentDiscount(IDiscount):
"""Implements a C# interface."""
@property
def Name(self) -> str:
return "student -10%"
def Apply(self, amount: decimal) -> decimal:
return amount - amount / 10
@dataclass
class LineItem:
name: str
price: decimal
qty: int = 1
class Cart:
def __init__(self, country: str) -> None:
self.country = country
self.lines: list[LineItem] = []
self.discounts: list[IDiscount] = []
def add(self, name: str, price: decimal, qty: int = 1) -> "Cart":
self.lines.append(LineItem(name, price, qty))
return self
def subtotal(self) -> decimal:
total: decimal = 0
for line in self.lines:
total += line.price * line.qty
return total
def total(self) -> decimal:
amount = self.subtotal()
for d in self.discounts:
amount = d.Apply(amount)
return amount * (1 + TaxRules.RateFor(self.country)) // Typhon code from pricing.ty, used from C# in the same project
var cart = new pricing.Cart("CH").add("book", 12.50m, 2).add("pen", 1.20m, 10);
cart.discounts.Add(new pricing.StudentDiscount());
Console.WriteLine($"subtotal {cart.subtotal():F2}, total incl. VAT after '{cart.discounts[0].Name}': {cart.total():F2}");
// A C# class deriving from a Typhon class (Typhon methods are virtual)
class LoudSquare(double side) : Polygon([new(0, 0), new(side, 0), new(side, side), new(0, side)])
{
public override string describe() => base.describe().ToUpperInvariant();
} subtotal 37.00, total incl. VAT after 'student -10%': 36.00
Limits of the current version
Typhon compiles a subset of Python, and in a few places its results differ from CPython. The repository documents these gaps. A selection:
complexand metaclasses are not supported yet.evalandexecwork only undertyphon run, which supplies a compiler at run time.- An
intis a checked 64-bit integer by default. A result beyond 64 bits raisesOverflowErrorunless big-int mode is switched on, which makes everyintunbounded and slower. - Objects follow CLR semantics. A
floatfield holds adouble, soPoint(3, 4)prints asPoint(x=3.0, y=4.0). CPython printsPoint(x=3, y=4). - Typhon.NumPy supports float64 arrays only. Its slices are copies, and some of its functions return dynamic values that Native AOT cannot compile.
Possible directions
On nine small benchmark programs, typed Python source compiled by Typhon ran 1.9 to 75 times faster than CPython, and the samples show Typhon and C# code in one assembly. Whether this holds for larger programs is an open question. If it does, the directions below become possible. The last of them draws on the roadmap ideas in the repository, which have no schedule.
-
Python syntax in .NET projects
A team that works in C# could write parts of an application in Python syntax and ship a single assembly. The target machine would need the .NET runtime and no Python installation.
-
Compiled scripts from the same source
Numeric scripts that are slow under CPython could run as compiled code with few changes, as long as they stay within the Python subset that Typhon supports. In the measurements, plain loops compiled by Typhon beat vectorized NumPy code on three of six problems.
-
Small native tools
Native AOT turns a Typhon program without dynamic values into one self-contained executable, and the benchmark programs came out at 1.5 to 1.9 MB. Executables like these could suit command-line tools and containers.
-
A broader language
The roadmap ideas include C# union types for
A | Bannotations,outandrefparameters as tuple returns, a faster big-int mode, a language server anddotnet newtemplates.
These are possibilities. The project has not committed to any of them.
Trying Typhon
Typhon needs the .NET 11 SDK. Clone the repository, build the solution and run one of the samples, which are ordinary .NET projects. Single scripts run with the typhon command, like python script.py. The quick start explains when to use which and covers the test suites.
git clone https://github.com/typhon-net/typhon-lang
cd typhon-lang
dotnet build Typhon.slnx
dotnet run --project samples/HelloTyphon