defregister(value): defwrap(func): if value in registry: raise ValueError( f"@value_dispatch: existing handler "f"registered for {value!r}" ) registry[value] = func return func
return wrap
defregister_for_all(values): defwrap(func): for value in values: if value in registry: raise ValueError( f"@value_dispatch: existing handler "f"registered for {value!r}" ) registry[value] = func return func
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- """ @date: 2021-11-17 16:20:03 @author: dreamhomes.top @description: test value dispatch. """ from dispatcher import valuedispatch
@valuedispatch defeat(fruit): returnf"I don't want a {fruit}..."
@eat.register("apple") def_eat_apple(fruit): return"I love apples!"
@eat.register("eggplant") @eat.register("squash") # or @eat.register_for_all({'eggplant', 'squash'}) def_eat_what(fruit): returnf"I didn't know {fruit} is a fruit!"
print(eat("apple")) >>> I love apples! print(eat("squash")) >>> I didn't know squash is a fruit!