Overloading.py is a Python 3 library that provides function and method dispatching based on the types and number of runtime arguments. When an overloaded function is called, it compares the arguments supplied to available signatures and invokes the implementation that provides the most accurate match. The library's current version is 0.5.0, released in April 2016, suggesting a low or inactive release cadence.
pip install overloadingVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to define multiple implementations of a function `biggest` using the `@overload` decorator. The library automatically dispatches to the correct implementation based on the runtime type of the `items` argument.
Ensure `@classmethod` or `@staticmethod` is placed below `@overload`:
```python
@overload
@classmethod
def my_method(cls, arg: int):
...
```
Always import `overload` from the `overloading` library (`from overloading import overload`) for runtime dispatch. If you only need type-checker hints without runtime behavior modification, use `from typing import overload` (Python 3.5+).
Consider `functools.singledispatch` for single-argument type-based dispatch (standard library, Python 3.4+) or `multimethod` for a more actively maintained third-party multiple-dispatch solution if long-term support and modern features are critical.
Due to a breaking change in v0.5, place `@staticmethod` or `@classmethod` *after* the `@overload` decorator.
```python
@overload
@staticmethod
def my_method(arg: str):
return f'Static method with {arg}'
```Define an `@overload` for the specific argument types being passed, or provide a more general overload (e.g., using `object`) that can act as a fallback. Ensure type hints accurately reflect expected inputs.
Refine the type hints in your `@overload` definitions to be more specific, ensuring that for any given set of arguments, only one overload provides the 'most accurate match'. This often means adding more specific type hints to resolve overlaps.