Browse the documentation

Typhon in a C# project

Add .ty files to an ordinary .csproj, configure the compiler with MSBuild properties and use Typhon code from C#.

Typhon compiles .ty files as part of a normal dotnet build, and dotnet run starts the result. The typhon command plays no part in a project build. A Roslyn source generator receives the files and adds the generated code to the project’s own compilation, so C# and Typhon code in one project can reference each other in both directions. The .NET SDK, MSBuild and Roslyn are used unchanged.

Project setup

The Typhon package is created from the repository with dotnet pack src/Typhon.Compiler. A project references it from a local package source:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net11.0</TargetFramework>
    <TyphonTypeMode>strict</TyphonTypeMode>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Typhon" Version="0.1.0" PrivateAssets="all" />
  </ItemGroup>
</Project>

Inside the Typhon repository, the samples get the same wiring from samples/Directory.Build.props. A project whose sources are .ty files only is still a .csproj, and dotnet run starts it like any console application.

MSBuild properties

PropertyValuesEffect
TyphonTypeModestrict, warn (default), permissiveDecides what happens where the compiler cannot determine a static type. Types and type inference describes the three modes.
TyphonIntModeint64 (default), bigintint64 compiles Python’s int to a checked 64-bit integer. bigint compiles it to an unbounded BigInteger, which is slower.
EnableDefaultTyphonItemstrue (default), falseWith true, the project compiles every **/*.ty file. With false, the project lists its files as <TyphonCompile Include="..." /> items. .gd files are compiled as GDScript when they are listed.
TyphonEmitToDiskfalse (default), trueWith true, the project does not use the source generator: a build step writes Typhon’s C# and runtime to TyphonEmitDir before the C# compiler runs. Other source generators then see Typhon’s classes, as Godot’s do in the sample Godot.

Modules as .NET types

Every .ty file is a module, and the compiler turns a module into a static class with the module’s name. Folders become namespaces under the project’s root namespace. In the samples, samples/TyphonLib/text/stats.ty becomes the class TyphonLib.text.stats, and C# calls its functions after using TyphonLib.text;:

Console.WriteLine($"top words: {string.Join(", ", stats.top_words(text, 2))}");

Classes defined in a module are nested in that static class. C# creates them with new and calls their methods. Typhon methods are virtual unless they are marked @final, so a C# class can derive from a Typhon class and override them:

var cart = new pricing.Cart("CH").add("book", 12.50m, 2).add("pen", 1.20m, 10);

class LoudSquare(double side) : Polygon([new(0, 0), new(side, 0), new(side, side), new(0, side)])
{
    public override string describe() => base.describe().ToUpperInvariant();
}

Names and visibility

Typhon keeps names as they are written, so calculate_area is calculate_area for C# callers as well. A leading underscore controls visibility:

Python nameC# visibility
namepublic
_nameinternal or protected internal
__nameprivate

Python protocols in C#

Typhon keeps Python’s protocol methods and connects them to their .NET counterparts. __eq__ becomes Equals and the == operator, __str__ becomes ToString, __getitem__ becomes an indexer, __iter__ makes the class implement IEnumerable<T>, and arithmetic methods such as __add__ become operators. A Typhon object therefore works in LINQ queries and data binding without wrappers.

A decorator that names no Python function becomes a .NET attribute, for example @Obsolete("...") or @Fact. On a property, typing.Annotated adds .NET attributes: title: Annotated[str, Required()] = "" declares a property with the [Required] attribute, as the Blazor samples do for form validation. With xUnit’s attributes, a project of .ty files is a test project that dotnet test runs, as in samples/XunitTests. Docstrings become XML documentation comments.

.NET base classes and events

A Typhon class can derive from a .NET class, and super().__init__() calls the base constructor. A method that overrides a virtual or abstract member of the base class keeps that member’s access, so def OnInitialized(self) in a subclass of Blazor’s ComponentBase becomes a protected override method. += subscribes a bound method or a lambda to a .NET event, as in button.Click += self.on_add. typing.cast(T, x) is a C# cast, and its result has the type T.

@STAThread on the function that starts a user interface also marks the Main that Typhon generates, because the CLR reads the COM apartment only from the entry point. Windows Forms, WPF and WinUI need it. The page Desktop apps shows all of this in one app per framework.

Exceptions between Typhon and C#

Python exception types map to .NET exception types. ValueError corresponds to ArgumentException and FormatException, and KeyError corresponds to KeyNotFoundException. An except ValueError clause in Typhon catches what .NET code throws, and C# catches what Typhon raises:

try { _ = new Circle(a, -1); }
catch (ArgumentException e) { Console.WriteLine($"Typhon raised ValueError → C# caught ArgumentException: {e.Message}"); }

Inferred signatures and C# callers

Typhon infers parameter types of unannotated functions from the calls in the project. A public function that the project calls only with int arguments therefore gets a long signature, the CLR type of Python’s int, and C# callers see that signature too. A function that only C# code calls has no call sites in Typhon code, so its unannotated parameters fall back to dynamic. Annotations on public functions avoid both effects.