Browse the documentation

Supported syntax and known gaps

The Python constructs Typhon compiles in its proof-of-concept state, and the ones it does not support yet.

Typhon adds no syntax of its own. Within Python’s syntax, the compiler handles the subset listed below.

Modules and imports

  • Modules and packages, with folders as namespaces.
  • import and from ... import of Typhon modules, of .NET namespaces and types, and of the Typhon standard library. lazy import (PEP 810) compiles to an ordinary import, since a compiled program binds its imports when it starts. In try: import x with an except ImportError: handler, the compiler resolves the import: it keeps the import when Typhon has the module and the handler when it does not.
  • An if __name__ == "__main__": block or a __main__.ty file as the entry point.

Functions

  • Default values, *args, keyword arguments and keyword-only parameters after *args.
  • **kwargs, which collects the extra keyword arguments in a dict. f(**d) passes a mapping as keyword arguments, also to a function without **kwargs, whose parameters the call then binds by name at run time.
  • Functions as values: a module function can be passed, assigned, stored in a container and returned.
  • PEP 695 generics (def f[T]) with bounds.
  • Lambdas, also stored in a variable, closures, global, nonlocal and globals().
  • Generators with yield and yield from, also with yield inside try, except and finally and inside expressions such as x = 2 * (yield x). A generator that receives values (x = yield v) or returns one supports send, throw, close and StopIteration.value.
  • Decorators written in Python on functions, nested functions, methods and classes, also stacked and with arguments, such as @trace, @repeat(3) and @functools.wraps(f). The decorated function is assigned where its def runs, so a memoizing decorator also sees recursive calls. A decorated method stays a method for C# callers. A class decorator runs where the class is defined and returns the class itself.
  • Function values called with *args, **kwargs and keyword arguments, attributes set on functions, functools.partial, and objects with __call__.
  • async def, await, async for and async with, compiled to .NET tasks. asyncio.run(main()) runs the coroutine on a single-threaded event loop, so coroutines switch only at await, as in Python, and run in a deterministic order. async with follows Python’s protocol of __aenter__ and __aexit__, and async comprehensions such as [x async for x in agen()] work.

Classes

  • Inheritance and super().
  • Multiple inheritance and mixins in Python’s method resolution order. super() follows that order, also across diamonds and in chains of __init__ methods, and isinstance(x, Mixin) holds for the classes a mixin is mixed into.
  • Properties with setters, @staticmethod and @classmethod, also written as name = property(getter, setter) or name = staticmethod(f) in the class body.
  • @abstractmethod with ABC, @override and @final.
  • @dataclass, with field(...), __post_init__, asdict, astuple, fields and replace.
  • Enum and IntEnum, with auto().
  • Named tuples from namedtuple(...), class P(namedtuple(...)) and class P(NamedTuple), with _replace, _asdict, _fields and _make.
  • Protocol, compiled to an interface that a class implements either structurally or explicitly.
  • PEP 695 generic classes (class Box[T]).
  • Class hierarchies with Base.__init__(self, ...), super(Cls, self) and method aliases such as __rmul__ = __mul__.
  • Classes defined inside a function, as long as they use none of its variables.
  • obj.__dict__ and vars(obj) as live views of an object’s attributes.
  • getattr, setattr, hasattr and delattr on properties, fields, class variables, methods and attributes added at run time.
  • Operator overloading through Python’s protocol methods.
  • A decorator that names no Python function becomes a .NET attribute, such as @Obsolete("..."). Docstrings become XML documentation.

Statements and expressions

  • if, elif and else, while, and for, including for ... else and while ... else. A counting loop over range compiles to a plain C# for loop.
  • match and case (PEP 634) with literal, capture, sequence, mapping, class and or-patterns, and guards.
  • The walrus operator :=, and type aliases with type Alias = ... (PEP 695).
  • try, except, else and finally, raise, and except A, B: (PEP 758).
  • sys.exit, which raises SystemExit. finally blocks run, except Exception does not catch it, and an uncaught SystemExit ends the program with its exit code.
  • with, following Python’s protocol of __enter__ and __exit__. An __exit__ that returns a true value suppresses the exception. For a .NET IDisposable, such as a file, with compiles to using. Several context managers can stand in parentheses, as in with (a() as x, b() as y):.
  • Starred unpacking: a, *rest = xs, [*a, *b], f(*args) and {**d1, **d2}.
  • Tuple unpacking, slice assignment, del xs[a:b], del d[key] and del xs[i], and del obj.attr and del name with the restrictions listed below.
  • List, dict and set comprehensions and generator expressions, compiled to LINQ.
  • f-strings with the format specification mini-language and f"{expr = }", the same quotes and nested f-strings inside replacement fields (PEP 701), and nested fields in format specifications, as in f"{x:>{width}}".
  • Template strings, t"..." (PEP 750), with string.templatelib.Template and Interpolation.
  • % formatting, as in "%s: %5.2f" % (name, v) and "%(key)s" % d.

Standard library

The Typhon runtime contains the Python builtins (print, len, range, sorted, format, frozenset and the methods of str, list, dict and set) and small versions of math, time, random and asyncio. os, os.path, sys and io behave as CPython’s on the platform the program runs on, with os.environ, os.stat, file descriptors, os.walk, binary and text streams and their base classes. The builtin exceptions carry Python’s attributes, and issubclass, dir, memoryview and frozendict exist. It also covers the commonly used parts of itertools, collections (Counter, defaultdict, deque, OrderedDict, namedtuple), functools (reduce, cmp_to_key, @cache, @lru_cache, wraps, partial, total_ordering), contextlib (contextmanager, suppress, nullcontext, closing, ExitStack), operator, string, fractions, pathlib, datetime, statistics, textwrap, base64, csv, glob, shutil, uuid, argparse, logging, threading, queue, concurrent.futures, contextvars, weakref, warnings, traceback, types, atexit, heapq, bisect, copy, json, re, array, struct, hashlib, hmac, tempfile, timeit and doctest, as well as bytes, bytearray and files opened in binary mode. socket provides TCP sockets, and select waits until sockets and other file descriptors are ready.

heapq uses CPython’s algorithm, so heaps print the same as in CPython, and json writes CPython’s output format. re runs on the .NET regex engine with Python’s syntax, group numbering and rules for sub, split and findall. asyncio provides gather, create_task, wait_for, as_completed, Queue, Lock, Event, Semaphore and TaskGroup. Typhon’s own doctest.testmod() runs no examples. With #:pylib, CPython’s doctest is compiled instead and runs them.

Typhon also ships the source of some of CPython’s modules, among them decimal, and compiles them with the program. With a #:pylib line, a script can also import other modules that the runtime lacks, which Typhon then compiles from CPython’s own source, as described in The typhon command.

datetime, statistics, textwrap, base64, csv, glob, shutil, uuid, argparse and logging are ports of CPython 3.14’s implementations and aim to print what CPython prints. Subclasses of their classes, such as a custom argparse.Action or logging.Handler, are not supported.

The runtime is compiled into every Typhon assembly as internal types, so a compiled program has no runtime dependency beyond .NET.

Known gaps

These constructs are not supported yet:

  • complex and metaclasses.
  • A decorator written in Python combined with @classmethod or @property on the same method, and a class decorator that returns something other than the class.
  • Enums with values other than integers.
  • eval, exec and compile in a program built with typhon build, where they raise NotSupportedException. Under typhon run they work, because the command supplies a compiler at run time.
  • Multiple inheritance from two .NET classes.
  • .NET out and ref parameters. The roadmap ideas include tuple returns for them, as in IronPython.
  • Integers beyond 64 bits outside big-int mode. They raise OverflowError.

Some constructs work with restrictions:

  • Static methods of generic classes need explicit type arguments, as in Stack[int].of(...).
  • Union types other than X | None compile to object.
  • An int compared with a float beyond 2**53 compares as a float.
  • .NET attributes that another source generator acts on, such as @JSExport, are emitted, but that generator does not see the code Typhon’s source generator produces. WebAssembly in the browser shows a workaround in C#. The MSBuild property TyphonEmitToDisk writes Typhon’s C# to disk before the build, so other source generators see it, as Godot’s do in the sample Godot.
  • A module cannot define a function with the module’s own name, such as def main() in main.ty.
  • Parameters are not inferred for methods that override or are overridden, decorated methods, methods of generic classes and methods a Protocol declares.
  • del obj.attr sets a field of the class back to its default value, so reading it afterwards gives that value, where Python raises AttributeError. del name leaves the name bound.
  • Threads run without a global interpreter lock, as in free-threaded CPython, so state that threads share needs a lock. A weak reference goes dead at a later garbage collection, not at once.
  • A coroutine starts running as soon as it is called. In Python it starts only when it is awaited or scheduled as a task. A task cannot be cancelled from outside.

Typhon.NumPy has its own list of limits. The conformance tests track the differences from CPython that are known.