Skip to main content
Classes in Sifr look and behave like Python classes, with one important difference: every field must have a type annotation, and the compiler verifies those types at compile time. You get the familiar class, def __init__, and self.field syntax with compile-time safety and zero runtime overhead.

Defining a Class

Declare fields as class-level annotations, then implement __init__ to accept and assign them. The compiler enforces that every field is initialized and that the types match throughout the class body.
Instantiate a class by calling it like a function. Field access uses standard dot notation.

Multiple Methods

A class can have as many methods as you need. Each method receives self as its first parameter, and the compiler enforces that the return type matches the annotation.

Classes in Union Types

Classes are first-class members of union types. Declare a parameter as Dog | Cat | Bird and the compiler tracks all three possibilities throughout the function body.
After an isinstance(shape, Circle) check, the compiler narrows shape to Circle inside the if block. In the else block it knows shape must be Square. You never need a cast.

isinstance Narrowing with Multi-Member Unions

When your union has more than two members, use elif chains. The compiler eliminates one variant per branch, leaving only the remaining possibilities.

Hashable Classes

Classes are hashable by default. Call hash() on any instance to get a deterministic integer hash based on its field values.

Error Subclasses

Subclass Error to define custom error types for use with Result[T, E]. Error subclasses carry typed fields just like any other class.
Error subclasses carry no hidden stack trace or exception machinery — only the fields you declare. They are lightweight typed values, not exception objects.
You consume them with try/except at the call site:

Class Design Guidelines

Keep classes small and focused on a single concept. Prefer multiple small classes in a union over a single large class with many optional fields.
Sifr does not support multiple inheritance. A class may subclass at most one base class, and only Error is a recognized base type at this time.