Overloading
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.
Common errors
-
TypeError: 'staticmethod' object is not callable
cause Incorrect decorator order where `@staticmethod` or `@classmethod` is placed before `@overload`.fixDue 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}' ``` -
overloading.errors.NoApplicableOverload: No applicable overload found for my_function(<class 'float'>)
cause An overloaded function was called with argument types for which no matching `@overload` implementation has been defined.fixDefine 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. -
overloading.errors.AmbiguityError: Ambiguous overloads for process_data(<class 'int'>, <class 'int'>)
cause The dispatcher found multiple `@overload` implementations that could equally match the given runtime arguments, leading to an ambiguous choice.fixRefine 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.
Warnings
- breaking Between v0.4 and v0.5, the treatment of `classmethod` and `staticmethod` was harmonized. These decorators must now appear *after* the `@overload` directive.
- gotcha Python does not have native function overloading; the `overloading` library provides runtime dispatch based on argument types. Do not confuse it with `typing.overload`, which is solely for static type checkers and does not affect runtime behavior.
- gotcha The library's last release was in 2016, indicating it is no longer actively maintained. While functional, it might not fully leverage newer Python features or integrate seamlessly with modern type-hinting patterns as well as alternatives like `functools.singledispatch` (for single-argument dispatch) or `multimethod` for more active maintenance.
Install
-
pip install overloading -
pip install typing
Imports
- overload
from typing import overload
from overloading import overload
Quickstart
from collections.abc import Iterable
from overloading import overload
@overload
def biggest(items: Iterable[int]):
return max(items)
@overload
def biggest(items: Iterable[str]):
return max(items, key=len)
print(biggest([2, 0, 15, 8, 7]))
print(biggest(['a', 'abc', 'bc']))