DEVELOPMENT EDITION · 769442725406
Vibe syntax
On this page

Vibe classes, interfaces, unions, and generics

Vibe implements specific statically typed class families. It does not run arbitrary Python class bodies or metaclasses. Choose the family whose value and dispatch rules fit the API: a dataclass is a record, a hierarchy can provide tagged dispatch, a Protocol is a nominal interface, and a PEP 695 generic supplies type-parameterized declarations.

Fields and construction

from dataclasses import dataclass
from verada import RangeInt

class Small(RangeInt, ge=0, le=10):
    pass

@dataclass
class Point:
    x: Small
    y: Small

This module fragment declares a scalar type and a two-field record. Fields require annotations. Supported class bodies hold fields, methods, a docstring, and placeholder pass; arbitrary executable class statements are not part of dataclass semantics. Instances are constructed with field values by keyword or by position, Point(x=2, y=3) or Point(2, 3); positions follow the fields' order, a parent's fields first. A dataclass of another module is constructed the same ways, imported by name or through its module (shapes.Point(2, 3)), except that by position every field is given (and one of a single field is given by keyword, as Level(5) of another module converts). Fields must meet their declared subtype constraints.

Construction is a record aggregate, not a call to Python's generated __init__. A field left out takes its default, as a dataclass's does: with x: int = 0, Point(y=3) has x 0. A field with no default must be given (B2010 otherwise). An empty collection field value (items=[], items={}, items=set()) gives the field an empty container of its own.

replace(p, x=7) (Python's dataclasses.replace, which verada exports) is a copy of the dataclass value p with the fields given changed, Ada's delta aggregate (P with delta X => 7).

The compiler supplies a dataclass's construction, equality and repr (Point(x=1, y=2), as Python's, where each field's type has a repr), so a dataclass does not define __init__ or __new__. Of Python's special methods a class may define __str__ and __repr__ (what print, str, repr and f-strings show), __eq__, __lt__, __le__, __gt__ and __ge__ (the comparisons), __add__, __sub__, __mul__, __truediv__ and __neg__ (the operators), __len__ (len(x)), __getitem__ and __setitem__ (x[k]), __contains__ (k in x), and __enter__ and __exit__, which make it a context manager for with. An operand's annotation may be a forward reference, other: "V". Others are B0401 (__invariant__, __initial__ and __del__ are an enclave's, enclaves). @dataclass(limited=True) is the one option a dataclass takes (its values are not copied, see enclaves); frozen=, slots=, order= and Python's other options are B0401, since Vibe would not keep their meaning. A class of another module is constructed through it as well, stock.Shelf([10, 20, 30]) or shapes.Point(x=1, y=2). Fields are the declared components, not a dynamic attribute dictionary. A ClassVar[T] annotation (count: ClassVar[int] = 0) is one variable for the class, shared by its instances as Python's class attribute is: Box.count names it, and so does self.count in the class's methods; a function that assigns it changes the module's state.

An ordinary dataclass is a value: assignment/copy and parameter rules must be understood together with sharing. Field access is point.x. A method decorated @property takes self alone and is read as a field, box.area; a property's setter is B0401.

Plain classes

A class without @dataclass whose __init__ makes its fields is a plain class, as in Python:

class Counter:
    def __init__(self, start: int, step: int = 1) -> None:
        self.n = start
        self.step = step

    def advance(self) -> None:
        self.n += self.step

Its fields are those __init__ assigns through self at its top level, in order, each of the type its annotation gives (self.n: int = start) or, failing one, the type of the parameter or value assigned (B0401 asks for the annotation when that is unknown). Counter(3) makes one: each field starts at its type's default, then __init__'s statements run. A field another method makes, or a branch of __init__, is B0401: every object has every field from the start. Otherwise a plain class is a dataclass: its methods, special methods and ClassVars are as above, and its objects follow the same sharing rules (a name bound to an object and then changed is a view of it). The design is in leno-plain-classes.md. Field names differing only in case from their type name are rejected. Keep field visibility consistent with the supported public/private record presentation.

Methods

A method starts with self; its annotation can be omitted. Other parameters and its result must be annotated. Component writes make self writable, and a method that both changes its object and returns a value is called as described in subprograms. A module-level function is the alternative when no receiver is needed.

Inherited and overridden methods follow the shared tagged-type rules: an override replaces the method for its class and its descendants, never for one object. A method's requires and ensures are its own contract; class-wide contracts are written in a Vada or Varc declaration.

Hierarchies and abstract classes

from abc import ABC, abstractmethod
from dataclasses import dataclass

class Shape(ABC):
    @abstractmethod
    def area(self) -> int: ...

@dataclass
class Square(Shape):
    side: Small

    def area(self) -> int:
        return int(self.side) * int(self.side)

This declaration fragment requires the Small type above. An abstract class and its supported derived dataclasses become tagged types. A parameter annotated with a tagged class, other than the method's own self, can accept supported subclasses. A call such as shape.area() can dispatch to the concrete override.

An abstract method's body is a placeholder (...) and is not compiled. A concrete method of an abstract class is inherited as usual. A class has at most one parent class with fields; further bases are Protocols, so Python's multiple inheritance of classes and its method resolution order do not arise.

Protocol interfaces

from typing import Protocol
from dataclasses import dataclass

class Labelled(Protocol):
    def label(self) -> int: ...

@dataclass
class Ticket(Labelled):
    code: int

    def label(self) -> int:
        return self.code

def label_of(value: Labelled) -> int:
    return value.label()

This form is exercised by the reference project. A Protocol body contains methods and optional documentation/placeholders, not arbitrary fields. Its operations are abstract. A concrete class implements the interface by naming it as a base; merely providing a same-named method is insufficient. No runtime structural isinstance check or automatic duck-typed conformance is implied. A class can name interfaces alongside its parent class.

Unions and class patterns

The accepted type union is a module-level alias joining supported classes declared in that module, normally dataclasses:

@dataclass
class Number:
    value: Small

@dataclass
class Mark:
    value: Small

type Token = Number | Mark

The compiler introduces a common abstract tagged root and derives the member classes from it, so a union joins classes of one module. A function taking Token can match a simple selector name using Number(value=n), Mark(value=n), and _. Positional pattern fields use the declared field order; keyword patterns name fields. Bindings are simple names or _, and are constant values of fields, not views of the object. The shared coverage and tag rules apply. Owned[Node] | None is the owner type that may be null; see sharing.

Generic functions

def choose[T](first: bool, a: T, b: T) -> T:
    if first:
        return a
    return b

def larger[T: Ordered](a: T, b: T) -> T:
    return b if a < b else a

Import Ordered from verada. T is a formal private type; Ordered additionally supplies a suitable less-than operation. Calls such as choose(True, 2, 3) and larger(4, 9) infer the actual type from the arguments. A bound naming a Protocol supplies that protocol's methods as formal subprograms. Generics are written in PEP 695 form; TypeVar declarations are Python's older spelling of the same and are not Vibe.

Generic dataclasses

@dataclass
class Box[T]:
    value: T
    count: int = 0

    def get(self) -> T:
        return self.value

The compiler makes a generic package containing the class and methods, with instances for the concrete uses it discovers in the module. Use an explicit target annotation for a constructor, such as box: Box[int] = Box(value=3, count=0). A generic class's parameter is a formal private type. Type arguments are named types.

Cross-module instance identity

An instance of a generic class whose type arguments are Python's own types (int, float, bool, str) is one library-level instance, shared by every module that names it: boxes.Box[float] in a client is the same type as Box[float] in boxes, whether or not boxes uses it itself, so values pass between them. An instance whose arguments name a module's own classes is declared in the defining module, after those classes; another module's Box[Point] names that one, which the defining module declares by using it (for example in a function profile taking Box[Point]). Qualified m.Box[T] follows the same rules.

For a plain dataclass Point, the compiler supplies list[Point] in its defining module. dict[int, Point] and set[Point] likewise name the defining module's instance, which that module declares by using it. The class corpus and the reference project show both. See shared generics for nominal identity and formal-operation contracts. Source evidence: class/generic lowering and instance inference.