Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

General protocols

These protocols cover iteration, comparison, operators, hashing, and freezing.

Iteration

  • Iterable[A]: values that can produce an iterator with __iter__ and can therefore be used in for loops and other iteration-based APIs

Iterator[A] is the class that holds traversal state. It also implements Iterable[A], so it can be used directly in a for loop. next(iterator) returns just(value) for the next item or nothing() when exhausted. Iterating an iterator continues from its current position rather than starting a new traversal.

See Generator expressions for lazy, single-pass iteration and flatmap examples.

Identity and comparison

  • Identity: identity comparison with is and is not
  • Eq: equality comparison with == and !=
  • Ord (Eq): ordering with <, <=, >, and >=

If you see a constraint such as A(Ord) in a type signature, it means values of type A support ordering.

Operator families

  • Logical: &, |, ^, and their in-place forms
  • Plus: +, +=, and __zero__
  • Minus: - and -=
  • Times[A] (Plus): * and *=, with right-hand operand type A
  • Div[A]: / and /=, with result type A

The in-place forms of Logical, Plus, Minus and Times can change their left operand and return it, as set, list, bytearray, bitset and bitarray do. The default implementations return a new value.

Hashing

  • Hashable (Eq): values that can feed data into a hasher; required for dictionary keys and set elements

If you see a constraint such as A(Hashable), values of type A can be used where hashing is required.

See Hashable for the full protocol reference and an implementation example.

Freezing

Freeze[A] provides a mutating freeze() -> A method. The global freeze(value) function calls this method and returns the immutable result of type A. For example, set[T] implements Freeze[iset[T]].

Freezing consumes the source value. The caller must own it exclusively and use only the result afterward. The compiler does not yet enforce this ownership requirement. See Freezing a set.