Experimenting with 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.

In [1]:
from functools import singledispatch, partial
from typing import *

The experiment

Dispatch different callable options for values, sequences, and containers.

In [10]:
@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)
        
In [11]:
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]

To Do

  • Add checks for containers and include and ordereddict example.
  • Redo ast-dispatch with singledispatch.

This effort will effect fidget later.