A Python library for managing multiple versions of dependencies
Maintained. Last release 5 months ago, commits in 1 of the last 26 weeks. Weaker on commit activity and contributor spread.
pip install pyvers🐦 pyvers
A Python library for dynamic dispatch based on module versions and backends.
What can you do with pyvers?
- 🔄 Handle breaking changes between different versions of a library without cluttering your code
- 🔀 Switch seamlessly between different backend implementations (e.g., CPU vs GPU)
- ✨ Support multiple versions of a dependency in the same codebase without complex if/else logic
- 🚀 Write version-specific optimizations while maintaining backward compatibility
- 🧹 Keep your code clean and maintainable while supporting multiple environments
Usage
pyvers lets you write version-specific implementations that are automatically selected based on the installed package version or backend. Here's a simple example using the register API (recommended):
from pyvers import implement_for, register_backend, get_backend, set_backend
# Register numpy backend - you could register more than one backend!
register_backend(group="numpy", backends={"numpy": "numpy"})
# Define the function with @implement_for, then register version-specific implementations
@implement_for("numpy")
def create_mask(arr):
"""Create a boolean mask marking positive values."""
raise NotImplementedError("No matching numpy version found")
# Function for NumPy < 2.0 (using bool8)
@create_mask.register(from_version=None, to_version="2.0.0")
def _(arr):
np = get_backend("numpy")
return np.array([x > 0 for x in arr], dtype=np.bool8)
# Function for NumPy >= 2.0 (using bool_)
@create_mask.register(from_version="2.0.0")
def _(arr):
np = get_backend("numpy")
return np.array([x > 0 for x in arr], dtype=np.bool_)
# The correct implementation is automatically chosen based on your NumPy version
result = create_mask([-1, 2, -3, 4])
print("NumPy result:", result)
The .register() API follows the same pattern as functools.singledispatch. Using _ as the function name is a Python convention that linters recognize, so you don't need # noqa comments.
Alternative: Traditional API
You can also use the traditional decorator pattern (requires # noqa: F811 for linters):
@implement_for("numpy", from_version=None, to_version="2.0.0")
def create_mask(arr):
np = get_backend("numpy")
return np.array([x > 0 for x in arr], dtype=np.bool8)
@implement_for("numpy", from_version="2.0.0")
def create_mask(arr): # noqa: F811
np = get_backend("numpy")
return np.array([x > 0 for x in arr], dtype=np.bool_)
Check out the examples folder for more advanced use cases: