bridge.models.decorators.dispatch#

Simplified dispatch system for Python, based on classes’ typeclass implementation.

This module provides a dispatch-based polymorphism system allowing extensible behavior for different types using the impl decorator.

Module Contents#

Classes#

_Dispatch

Internal dispatch representation with type-based routing logic.

Functions#

dispatch

Create a new dispatch function from a signature.

Data#

API#

bridge.models.decorators.dispatch._SignatureType#

‘TypeVar(…)’

class bridge.models.decorators.dispatch._Dispatch(signature: Callable)#

Internal dispatch representation with type-based routing logic.

Initialization

__slots__#

(‘_signature’, ‘_name’, ‘_exact_types’, ‘_dispatch_cache’, ‘_doc’, ‘_module’)

__call__(instance: Any, *args, **kwargs) Any#

Dispatch to the appropriate implementation based on instance type.

impl(
*target_types: Any,
) Callable[[Callable], Callable]#

Register an implementation for one or more types.

Usage: @mydispatch.impl(int) # Register for a single type @mydispatch.impl(int, str) # Register for multiple types @mydispatch.impl((list, str)) # Register for a tuple of types as a key

__repr__() str#

Rich representation showing all implementations.

_dispatch(
instance: Any,
instance_type: type,
) Optional[Callable]#

Find the implementation for a given type.

_format_location(func: Callable) str#

Format the location of a function for display.

_format_no_implementation_error(instance: Any) str#

Format a helpful error message when no implementation is found.

bridge.models.decorators.dispatch.dispatch(
func: bridge.models.decorators.dispatch._SignatureType,
) bridge.models.decorators.dispatch._Dispatch#

Create a new dispatch function from a signature.

Parameters:

func – Function defining the dispatch signature and default behavior

Returns:

A dispatch object that can be extended with implementations

.. rubric:: Example

@dispatch … def to_string(instance) -> str: … ‘’’Convert instance to string representation.’’’ … @to_string.impl(int) … def _to_string_int(instance: int) -> str: … return str(instance) … @to_string.impl(list, tuple) … def _to_string_sequence(instance) -> str: … return ‘, ‘.join(map(str, instance)) … assert to_string(42) == “42” assert to_string([1, 2, 3]) == “1, 2, 3”

bridge.models.decorators.dispatch.__all__#

[‘dispatch’]