In [1]:
"""setup"""
from whatever import *
from toolz.curried import *
from whatever.callables import Dispatch
from collections import OrderedDict
from typing import Callable, Any
In [2]:
"""test_subclass"""
assert isinstance(Dispatch(), OrderedDict)
assert isinstance(Dispatch(), Callable)
In [3]:
"""dict_input"""
d = Dispatch({
int: int,
str: int,
})
assert isinstance(d("0"), int)
assert isinstance(d(0), int)
In [4]:
"""list_input"""
d = Dispatch([
[int, int],
[str, int],
])
assert isinstance(d("0"), int)
assert isinstance(d(0), int)
In [5]:
"""list_input"""
d = Dispatch([
[type(None), lambda x: 'empty'],
[Any, lambda x: 'not empty'], # catch all
])
assert d(None) == 'empty'
In [6]:
"""list_input"""
d = Dispatch([
[Any, lambda x: 'not empty'],
[type(None), lambda x: 'empty'],
])
assert d(None) == 'not empty'
In [7]:
"""test_arity"""
d = Dispatch({
(str, int): lambda x, y: str(x) + str(y)
})
assert d('test',1) == 'test1'
In [8]:
"""test_arity_multiclas"""
d = Dispatch({
((str, int,), int): lambda x, y: str(x) + str(y)
})
assert d(10000,1) == ''.join([str(10000),str(1)])
In [10]:
d = Dispatch({
str: str.upper,
int: lambda x: x/100,
})
f = _x({
'a': 'car',
'b' : 20,
}) | valmap(d)
assert f._() == {'a': 'CAR', 'b': 0.2}
f.compute()
Out[10]:
In [11]:
d = Dispatch({
str: str.upper,
(int, int,): lambda x, y: x*y,
})
f = _x({
'a': 'car',
'b' : [20, 10],
}) | valmap(lambda a: d(*a) if isinstance(a, list) else d(a))
assert f._() == {'a': 'CAR', 'b': 200}
f._()
Out[11]: