Browse the documentation

Semantics

Where Typhon follows the CLR and where it follows Python: objects, integers, operators, sequences, formatting and exceptions.

Typhon uses CLR semantics for types and objects: classes have a fixed layout, types are nominal, and objects compare by reference unless they define __eq__. It follows Python’s semantics where that is cheap and where Python programmers expect it. The conformance tests compare many of these rules with CPython.

Objects and fields

A field with an annotation holds a value of the corresponding CLR type. A float field is a double, so the value is converted when an int is assigned to it:

@dataclass
class Point:
    x: float
    y: float

print(Point(3, 4))

Typhon prints Point(x=3.0, y=4.0). CPython prints Point(x=3, y=4), because Python does not check or convert annotated values.

Integers

An int is a 64-bit long, and arithmetic on it is checked, so it never wraps around. sum(range(100000)), factorial(20) and 2 ** 62 give CPython’s result. A result beyond 64 bits raises OverflowError, where CPython would switch to arbitrary precision.

Big-int mode makes int a System.Numerics.BigInteger, unbounded like Python’s. It is switched on with typhon run --bigint, with <TyphonIntMode>bigint</TyphonIntMode> in a project, or with a # typhon: int=bigint comment in any module, and it then applies to the whole program. Range counters and len() stay 64-bit and are widened where an operation could leave 64 bits. factorial, pow, gcd and similar functions use exact BigInteger overloads. Big-int mode is slower than the 64-bit mode.

Where a .NET API expects an int, for example a list index, s.PadLeft(n), List.Insert(i, x) or DateTime(y, m, d), Typhon narrows the value with an overflow check. Overloads that accept a long, such as Math.Max, receive the long. A .NET integer read into a Python variable (n = sb.Length) becomes a Python int, and int32(x), uint8(x) and similar functions convert explicitly. << and >> shift like Python, without the modulo-64 behaviour of C#.

Operators and truth values

  • / is true division and // is floor division. % takes the sign of the divisor, and ** is the power operator.
  • Conditions use Python’s truth values, so if items: tests for a non-empty list. x or y and x and y return the deciding operand.
  • Chained comparisons, in, not in and is None work as in Python.
  • == compares the contents of lists, dicts, sets and tuples. < orders sequences lexicographically and sets by inclusion.
  • bool is an integer, so True + True is 2.
  • An int compared with a float beyond 2**53 compares as a float, which can differ from CPython.

Sequences, strings and dictionaries

Slicing clamps to the bounds and accepts negative indices and steps (s[::-1]). [0] * n, "-" * 40 and list + list work as in Python, and xs += ys extends the list in place. A computed negative position counts from the end, for example xs[-k] or xs[i - 1] at i == 0. The compiler leaves this check out where it can show that a position is non-negative, for example for range counters or for j inside while i < j:, so hot loops do not pay for it.

The elements of a str are one-character strings. A dict keeps insertion order, and iterating over it yields its keys. A range is a sequence that supports r[-1], len(r) and x in r.

Functions as values

A module function that is passed, assigned, stored or returned is a value with its own type, an instance of a generated PyFunction subclass. A parameter that receives such a function is specialised for it, so apply(f, x) calls f directly and with static types. Where the type is lost, for example in a dict of handlers, the value stays callable, and print(f) shows <function f at 0x...>. A function that can reach its end without return returns None there.

Classes and construction

Class hierarchies keep Python’s dynamic lookup where programs rely on it. A method that only subclasses define gets a stub in the base class, which raises AttributeError, and overrides agree on one return type. Assignments such as obj.attr = v from outside a class, or Cls.CONST = v after it, declare fields. Class variables can be read through self, self.__class__ or type(self).

A subclass that sets attributes before it calls super().__init__() gets Python’s two-phase construction. The object is allocated first, and the __init__ methods then run in the order Python runs them, so the base class’s __init__ can call overridden methods that read those attributes.

Tuples and named tuples

Short tuples with items of different types stay C# value tuples. A long tuple of one item type, and tuples of different lengths in one literal, become sequences of the type PyTuple<T>, so concatenation, repetition, slicing and sum(..., ()) work as in Python.

Named tuples support unpacking, indexing, iteration, len, equality, hashing and ordering, and they print as P(x=1, y=2). Their field types are inferred from the calls that create them.

Rebinding and narrowing

A name that is rebound to a value of another type, as in n = str(n), becomes a new variable. If the rebinding happens in a nested block, the variable gets a wider type: float where possible, dynamic otherwise. if x is not None: narrows an int | None to int inside the block.

Values of unknown type

A dynamic value still supports Python’s methods for str, list and dict (d.strip(), "".join(d)), unpacking (a, b = d), iteration and indexing (d[k], d[i] += 1). Files read lines with exactly the newline characters they contain.

Late-bound values follow Python’s rules in more places than C# would. A late-bound value can be called when it holds a function, an object with __call__ or a class, and a list that receives both ints and floats holds both.

Printing and formatting

print, str, repr and f-strings format values like CPython: True, None, [1, 2], {'a': 1}, 1.0 and Color.RED. f-strings support the Python format specification mini-language and the f"{expr = }" form. % formatting works as in CPython, with a tuple ("%s: %5.2f" % (name, v)) or a mapping ("%(key)s" % d).

Exceptions

Python exception types map to .NET exception types, for example ValueError to ArgumentException and FormatException, and KeyError to KeyNotFoundException. except ValueError therefore catches what .NET code throws, and C# code catches what Typhon raises.