singledispatch
¶I have used multipledispatch
quite often, and the API is quite similar to singledispatch
. For packages and modules, I would prefer to use singledispatch
because it is standard lib in python 3.
from functools import singledispatch, partial
from typing import *
Dispatch different callable options for values, sequences, and containers.
@singledispatch
def functor(f, *args, **kwargs):
return f(*args, **kwargs) if callable(f) else f
@functor.register(Sequence)
def _(fns, *args, **kwargs):
return type(fns)([
functor(f, *args, **kwargs) for f in fns])
@functor.register(
issubclass(Mapping, Container) and Container or Mapping
)
def _(fns, *args, **kwargs):
return type(callables)((
functor(k, *args, **kwargs),
functor(fns[k], *args, **kwargs)
) for k in fns)
assert functor(1) is 1
assert functor(lambda x: x, 1) is 1
assert functor([lambda x: x], 1) == [1]
assert functor([lambda x: x, lambda x: 2*x, ], 1) == [1, 2]
This effort will effect fidget
later.