How to use multimethod - 10 common examples

To help you get started, we’ve selected a few multimethod examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github coady / multimethod / tests / test_all.py View on Github external
@multimethod(object, bracket)
def join(seq, sep):
    return sep[0] + join(seq, sep[1] + sep[0]) + sep[1]
github coady / multimethod / tests / test_all.py View on Github external
@multimethod(paper, rock)
def roshambo(left, right):
    return 'paper covers rock'
github coady / multimethod / tests / test_all.py View on Github external
@multimethod(tree, object)
def join(seq, sep):
    return join(seq.walk(), sep)
github coady / multimethod / tests / test_all.py View on Github external
@multimethod(rock, scissors)
def roshambo(left, right):
    return 'rock smashes scissors'
github coady / multimethod / tests / test_all.py View on Github external
@multimethod(scissors, rock)
@multimethod(rock, scissors)
def roshambo(left, right):
    return 'rock smashes scissors'
github coady / multimethod / tests / test_methods.py View on Github external
def test_get_type():
    method = multimethod(lambda: None)
    assert method.get_type is type

    @method.register
    def _(x: Union[int, type(None)]):
        pass

    assert method.get_type is type

    @method.register
    def _(x: List[int]):
        pass

    assert method.get_type is get_type
github coady / multimethod / tests / test_all.py View on Github external
@multimethod(object, object)
def roshambo(left, right):
    return 'tie'
github coady / multimethod / tests / test_methods.py View on Github external
@multimethod
def func(arg: bool):
    return bool
github coady / multimethod / tests / test_dispatch.py View on Github external
assert roshambo(r, p) == 'paper covers rock'
    assert roshambo(p, r) == 'paper covers rock'
    assert roshambo(r, s) == 'rock smashes scissors'
    assert roshambo(p, s) == 'scissors cut paper'
    assert roshambo(r, r) == 'tie'
    assert len(roshambo) == 8
    del roshambo[()]
    del roshambo[rock, paper]
    assert len(roshambo) == 5
    with pytest.raises(DispatchError, match="0 methods"):
        roshambo(r, r)


# methods
class cls(object):
    method = multidispatch(lambda self, other: None)

    @method.register(Iterable, object)
    def _(self, other):
        return 'left'

    @method.register(object, Iterable)
    def _(self, other):
        return 'right'


def test_cls():
    obj = cls()
    assert obj.method(None) is cls.method(None, None) is None
    assert obj.method('') == 'right'
    assert cls.method('', None) == 'left'
    with pytest.raises(DispatchError, match="2 methods"):
github coady / multimethod / tests / test_all.py View on Github external
    @multidispatch
    def func(arg):
        return type(arg)