API Reference

This page documents the public API exported by alternative.

Decorator

alternative.reference(implementation=..., *, default=False)

Create an Alternatives set from its trusted reference implementation.

Use @reference, @reference(default=True), or reference(implementation). The reference is the implicit runtime default until another implementation is registered with default=True.

Parameters:
  • implementation – The trusted function, callable, or method descriptor. Place this decorator outside classmethod or staticmethod.

  • default – Make the reference the explicit default, preventing another registration from selecting a default.

Returns:

An Alternatives wrapper, or a decorator returning one when called without an implementation. Decorated callables keep their typed call signatures for normal calls and code completion.

Alternatives

class alternative.Alternatives(implementation, *, default=False)

Manage a reference, its candidates, and one stable runtime default.

Usually created by reference(). Register every candidate before calling the set or measure(), reading callable or implementations, or applying a pytest helper to a test function.

property reference

Return the immutable reference implementation.

property callable

Return the selected callable and prevent further registration.

Call this callable directly to use the selected implementation without dispatch through the alternatives object.

property implementations

Return an immutable snapshot and prevent further registration.

__call__(*args, **kwargs)

Call self as a function.

measure(operator, *args, **kwargs)

Score each implementation’s returned result with the given operator.

For example, use measure(len, data) to compare compressed output sizes after checking that each implementation decodes to the original data. This scores outputs; use a benchmark to measure elapsed time.

Return a dictionary keyed by Implementation objects, ordered by ascending score when scores are sortable, or by registration order otherwise. Arguments are shared without copying. Measurement freezes registration and keeps the selected default unchanged.

Alternatives.add(implementation=..., *, default=False)

Register a compatible candidate and return its Implementation wrapper.

Omit implementation to obtain a decorator, as in @function.add(default=True). Direct calls and @function.add also work. Calling the returned wrapper invokes that candidate directly.

Parameters:
  • implementation – A callable, matching method descriptor, or another alternatives set whose reference should be copied.

  • default – Select this candidate for normal calls. Only one explicit default may be registered, including an explicitly selected reference.

Raises:
Returns:

An Implementation, or a decorator returning one when called without an implementation.

Alternatives.pytest_parametrize(test=..., *, only_default=False)

Decorator to parametrise a test function with implementations - always includes the reference implementation.

Parameters:
  • test – Test function to wrap - this is elided if using the decorator syntax.

  • only_default – Only include the reference and default implementations. If False, include all implementations.

Alternatives.pytest_parametrize_pairs(test=..., *, n_cache=0, double_reference=False, only_default=False)

Decorator to parametrise a test function with the reference and alternative implementations.

Parameters:
  • test – Inner pytest function to parameterise with reference and alternative implementations - this is elided if using the decorator syntax.

  • n_cache – Number of reusable reference results to cache. Use a positive size for a bounded cache, None for an unbounded cache, or 0 to disable caching. Cached calls require hashable arguments and results that are safe to share.

  • double_reference – If True, the reference implementation will be included in the implementations. This can be used for sanity-checking equivalence tests.

  • only_default – If True, only the default implementation will be used as the other implementation. If double_reference is True, the reference implementation will be included as well.

Raises:

ValueError – If caching is enabled for an asynchronous or generator reference.

The ellipsis in these signatures means the implementation or test may be omitted for decorator-factory syntax. It is not a value to pass to the API. Runtime registration does not validate signature compatibility; type checkers validate the registration contracts in Typing and IDEs.

Implementation

class alternative.Implementation(alternatives, implementation, label=None)

An immutable registered candidate that remains directly callable.

alternatives identifies its registry, implementation exposes the raw callable or descriptor, and label contains an optional debug call site. Calling a candidate directly does not select it as the registry’s default.

__call__(*args, **kwargs)

Call self as a function.

Implementation.add(implementation=..., *, default=False)

Forward registration to the parent Alternatives set.

Accept the same direct-call and decorator forms as Alternatives.add(), returning an Implementation or its decorator.

Exceptions

exception alternative.AlternativeError

Base class for all alternative errors.

exception alternative.AddTooLateError

Cannot add implementations after invocation or inspection.

exception alternative.MultipleDefaultsError

Cannot set the default implementation more than once.

exception alternative.CrossAlternativesImplementationError

Cannot add an Implementation object that belongs to a different Alternatives set.

Typing and IDEs

Decorated functions keep their declared parameter and return types, including parameter names, defaults, and keyword-only arguments. You can register candidates and select a default in registration code while callers keep the same typed interface and code completion. Keep using ordinary function annotations.

Candidates must accept all calls permitted by the reference and return a compatible type. Mypy, Pyright, and Pyrefly check these requirements; runtime registration does not validate signatures. Annotations describe accepted calls, while your tests establish behavioral equivalence.

Methods keep normal receiver binding. An instance supplies self, and a class method supplies cls; ordinary function arguments remain explicit. See Methods and Descriptors for examples.

Runtime tools such as inspect.signature() also see the original signature, name, and documentation. The alternatives object describes the reference’s public contract, and each candidate describes its own implementation. Inspecting this metadata does not freeze registration.

Some IDEs can report incorrect warnings for decorated keyword calls or bound methods. If your IDE and type checker disagree, report a minimal example. These diagnostic limitations do not change runtime calls.