+class Dispatcher:
+ r"""Dispatcher([routes]) -> Dispatcher instance :: Command dispatcher
+
+ This class provides a modular and extensible dispatching mechanism. You
+ can specify root 'routes' (as a dict where the key is the string of the
+ root command and the value is a callable object to handle that command,
+ or a subcommand if the callable is an instance and the command can be
+ sub-routed).
+
+ The command can have arguments, separated by (any number of) spaces.
+
+ The dispatcher tries to route the command as deeply as it can, passing
+ the other "path" components as arguments to the callable. To route the
+ command it inspects the callable attributes to find a suitable callable
+ attribute to handle the command in a more specific way, and so on.
+
+ Example:
+ >>> d = Dispatcher(dict(handler=some_handler))
+ >>> d.dispatch('handler attribute method arg1 arg2')
+
+ If 'some_handler' is an object with an 'attribute' that is another
+ object which has a method named 'method', then
+ some_handler.attribute.method('arg1', 'arg2') will be called. If
+ some_handler is a function, then some_handler('attribute', 'method',
+ 'arg1', 'arg2') will be called. The handler "tree" can be as complex
+ and deep as you want.
+
+ If some command can't be dispatched (because there is no root handler or
+ there is no matching callable attribute), a CommandNotFoundError is raised.
+ """
+
+ def __init__(self, routes=dict()):
+ r"""Initialize the Dispatcher object.
+
+ See Dispatcher class documentation for more info.
+ """
+ self.routes = routes
+
+ def dispatch(self, route):
+ r"""dispatch(route) -> None :: Dispatch a command string.
+
+ This method searches for a suitable callable object in the routes
+ "tree" and call it, or raises a CommandNotFoundError if the command
+ can't be dispatched.
+ """
+ command = list()
+ route = route.split() # TODO support "" and keyword arguments
+ if not route:
+ raise CommandNotFoundError(command)
+ command.append(route[0])
+ handler = self.routes.get(route[0], None)
+ if handler is None:
+ raise CommandNotFoundError(command)
+ route = route[1:]
+ while not is_handler(handler):
+ if len(route) is 0:
+ raise CommandNotFoundError(command)
+ command.append(route[0])
+ if not hasattr(handler, route[0]):
+ raise CommandNotFoundError(command)
+ handler = getattr(handler, route[0])
+ route = route[1:]
+ return handler(*route)