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.
importandfrom ... importof 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. Intry: import xwith anexcept 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__.tyfile 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,nonlocalandglobals(). - Generators with
yieldandyield from, also withyieldinsidetry,exceptandfinallyand inside expressions such asx = 2 * (yield x). A generator that receives values (x = yield v) or returns one supportssend,throw,closeandStopIteration.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 itsdefruns, 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,**kwargsand keyword arguments, attributes set on functions,functools.partial, and objects with__call__. async def,await,async forandasync with, compiled to .NET tasks.asyncio.run(main())runs the coroutine on a single-threaded event loop, so coroutines switch only atawait, as in Python, and run in a deterministic order.async withfollows 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, andisinstance(x, Mixin)holds for the classes a mixin is mixed into. - Properties with setters,
@staticmethodand@classmethod, also written asname = property(getter, setter)orname = staticmethod(f)in the class body. @abstractmethodwithABC,@overrideand@final.@dataclass, withfield(...),__post_init__,asdict,astuple,fieldsandreplace.EnumandIntEnum, withauto().- Named tuples from
namedtuple(...),class P(namedtuple(...))andclass P(NamedTuple), with_replace,_asdict,_fieldsand_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__andvars(obj)as live views of an object’s attributes.getattr,setattr,hasattranddelattron 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,elifandelse,while, andfor, includingfor ... elseandwhile ... else. A counting loop overrangecompiles to a plain C#forloop.matchandcase(PEP 634) with literal, capture, sequence, mapping, class and or-patterns, and guards.- The walrus operator
:=, and type aliases withtype Alias = ...(PEP 695). try,except,elseandfinally,raise, andexcept A, B:(PEP 758).sys.exit, which raisesSystemExit.finallyblocks run,except Exceptiondoes not catch it, and an uncaughtSystemExitends 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 .NETIDisposable, such as a file,withcompiles tousing. Several context managers can stand in parentheses, as inwith (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]anddel xs[i], anddel obj.attranddel namewith 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 inf"{x:>{width}}". - Template strings,
t"..."(PEP 750), withstring.templatelib.TemplateandInterpolation. %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:
complexand metaclasses.- A decorator written in Python combined with
@classmethodor@propertyon the same method, and a class decorator that returns something other than the class. - Enums with values other than integers.
eval,execandcompilein a program built withtyphon build, where they raiseNotSupportedException. Undertyphon runthey work, because the command supplies a compiler at run time.- Multiple inheritance from two .NET classes.
- .NET
outandrefparameters. 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 | Nonecompile toobject. - An
intcompared with afloatbeyond 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 propertyTyphonEmitToDiskwrites 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()inmain.ty. - Parameters are not inferred for methods that override or are overridden, decorated methods, methods of generic classes and methods a
Protocoldeclares. del obj.attrsets a field of the class back to its default value, so reading it afterwards gives that value, where Python raisesAttributeError.del nameleaves 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.