Skip to main content

PyPi Package Build Status Coverage Report Documentation Status

alternative

A dependency-free library for managing multiple implementations of the same function — especially when you're iterating toward faster or cleaner versions and want those choices to stay explicit, testable, and safe.

Full documentation is available on Read the Docs. The documentation source lives in docs/.

Why use this?

When optimizing a hot path, it’s common to accumulate:

  • a trusted reference implementation
  • one or more candidate rewrites
  • tests to keep them equivalent
  • benchmarks to validate wins

alternative keeps that workflow tidy by making implementation registration and selection first-class.

The same model works for module functions, instance methods, class methods, and static methods. Public typing is shipped in alternative/__init__.pyi, so supported type checkers can retain decorated call signatures.

Quick example

import alternative


@alternative.reference
def constant_number():
    return 1


@constant_number.add(default=True)
def alternative_constant_number():
    return 2


@constant_number.add
def unused_alternative_constant_number():
    return 3


# the default=True implementation is used if specified;
# otherwise, the reference is the implicit default
assert constant_number() == 2
# alternative implementations still act like themselves
assert unused_alternative_constant_number() == 3

See the quickstart for registration patterns, defaults, and method examples.

Methods and descriptors

Decorate instance methods directly. For @classmethod and @staticmethod, put @alternative.reference and .add(...) outside the built-in descriptor decorator:

import alternative


class Parser:
    def __init__(self, value: str = ""):
        self.value = value

    @alternative.reference
    def parse(self, value: str) -> int:
        return int(value.strip())

    @parse.add(default=True)
    def parse_fast(self, value: str) -> int:
        return int(value)

    @alternative.reference
    @classmethod
    def from_text(cls, value: str) -> "Parser":
        return cls(value.strip())

    @from_text.add(default=True)
    @classmethod
    def from_text_fast(cls, value: str) -> "Parser":
        return cls(value)

    @alternative.reference
    @staticmethod
    def is_valid(value: str) -> bool:
        return value.strip().isdigit()

    @is_valid.add(default=True)
    @staticmethod
    def is_valid_fast(value: str) -> bool:
        return value.isdigit()

Calling through an instance or class follows normal Python binding rules, and direct implementation calls bind the same way. The full descriptor examples are in Use Methods and Testing Methods.

Pytest features

The pytest helpers are documented in the pytest integration guide.

Pairwise equivalence checks

Use pytest_parametrize_pairs(...) to compare the reference against each candidate implementation.

Single-implementation parametrization

Use pytest_parametrize(...) to run one test body across all implementations.

Runtime tools

Alternatives.measure(...) runs every implementation with the same arguments and measures the results with a callable you provide. See Measure Implementations.

Safety guarantees

The library tries to avoid unpleasant surprises caused by import order or accidental state changes:

  • The selected implementation cannot be changed once it has been used.
  • Implementations cannot be added once they have been inspected, reducing the chance that tests only covered a subset.

Debug mode

Set ALTERNATIVE_DEBUG=1 to record where critical state changes happened (like selecting defaults or inspecting implementations). These locations are surfaced in error messages to make stateful issues easier to track down.

When debug mode is enabled, each Implementation also captures a label with its registration call-site. This label appears in repr(...) and selected debug errors, making it easier to disambiguate implementation instances.

Typing and IDEs

alternative ships its stub file and py.typed marker in the installed package. The public typing surface lives in alternative/__init__.pyi; runtime behavior lives in alternative/__init__.py.

CI checks the typing probes with mypy, Pyright, and Pyrefly. scripts/pycharm-type-probes.sh separately checks type assertions, argument lists, unresolved references, and type warnings in typing_tests/type_probes.py. It uses a disposable project with the repository's Python environment and requires deliberate failure controls to be detected before accepting a clean result.

PyCharm 2026.2.3 has known gaps in ParamSpec return inference, variadic calls, and receiver binding. typing_tests/pycharm_xfails.json records the exact expected diagnostics and related JetBrains issues. Unexpected diagnostics or passes fail the check; scripts/pycharm-type-probes.sh --show-xfails lists the recognised cases. Every assertion remains enabled for mypy, Pyright, and Pyrefly. The separate PyNestedDecoratorsInspection false positive for decorators outside @classmethod or @staticmethod is excluded from this check.

Metadata

Release files for alternative 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for alternative 0.3.0
File Size Uploaded Provenance Actions
alternative-0.3.0.tar.gz 127.7 kB With provenance Details for alternative-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for alternative 0.3.0
File Interpreter ABI Platform Actions
alternative-0.3.0-py3-none-any.whl Python 3 none any Details for alternative-0.3.0-py3-none-any.whl

Total release size: 139.4 kB

Release files / alternative-0.3.0.tar.gz

Download URL alternative-0.3.0.tar.gz
Size 127.7 kB
Tags Source
SHA-256 checksum
How to use checksums
c95b2c15a5d1fdb3568c2d88dc15ec8eae1d7f78071a2f49b9b1e8bb66301f8e
BLAKE2b-256 checksum
How to use checksums
6a889038f5e04d7d70759d831f1dc4e7f1d56569e306beaef52c0f3371af3bb3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 18, 2026.

Transparency log

Release files / alternative-0.3.0-py3-none-any.whl

Download URL alternative-0.3.0-py3-none-any.whl
Size 11.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3f70f53f4ce55c5625ec71dbd819d6d579318c2098db33720858071a90b20143
BLAKE2b-256 checksum
How to use checksums
49e88662969b94da94509f492bd8843f08d81287eb2cdcbce0ed44618d892f85
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 18, 2026.

Transparency log

Security for alternative 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for alternative-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 18, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page