Class: Dispatch | ./src/peak/util/dispatch.py | |||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Mapping from rules to objects (slow, but simple) This is a generic rule-driven lookup table that finds the "closest matches"
based on whether a supplied key matches rules in the table, returning
results for the most-specific rules first. It can be used to
implement business rules, stylesheets, generic functions, multimethods,
or anything else you can think of that needs prioritized rule-driven
matching. All you need are objects that implement the Note that Usage: # Dispatcher that doesn't hold references to looked-up objects dispatcher = Dispatch(WeakKeyDictionary()) dispatcher[aBusinesRule] = actionToTake # Retrieve action for closest match -- error if none found or ambiguous actionToTake = dispatcher[aBusinessObject].next() PerformanceThe principal drawback of this class is speed. Although lookups are cached, each new uncached lookup requires a loop over all the rules in the table, with each rule being asked to match the key being looked up. Then, the matching rules are sorted to put them in "closest-match-first" order, and this uses many function calls per comparison. However, for many simple applications of rule-based dispatching (such as multiple-dispatch of generic functions), where there aren't too many rules and even fewer that match on any given lookup, performance should be acceptable. For more complex applications, you'll want a more sophisticated dispatcher that has internal indexes for its rules. But, you can always use this dispatcher as a prototype to get the rest of your system figured out first.
|
__init__
|
| __init__ ( self, items=(), cache=None, ) Create dispatcher from
|
|||||||||||||||
__setitem__ | ||||||||||||||||||
__setitem__ ( self, rule, result, ) Store |