Here is a more generalized version using Python decorators. You can call by short or long name. I found this useful when implementing CLIs with short and long subcommands.
Python decorators are great. Bruce Eckel (Thinking in Java) beautifully describes Python decorators.
http://www.artima.com/weblogs/viewpost.jsp?thread=240808 http://www.artima.com/weblogs/viewpost.jsp?thread=240845
#!/usr/bin/env python2 from functools import wraps class CommandInfo(object): cmds = [] def __init__(self, shortname, longname, func): self.shortname = shortname self.longname = longname self.func = func class CommandDispatch(object): def __init__(self, shortname, longname): self.shortname = shortname self.longname = longname def __call__(self, func): print("hello from CommandDispatch __call__") @wraps(func) def wrapped_func(wself, *args, **kwargs): print('hello from wrapped_func, args:{0}, kwargs: {1}'.format(args, kwargs)) func(wself, *args, **kwargs) ci = CommandInfo ci.cmds += [ci(shortname=self.shortname, longname=self.longname, func=func)] return wrapped_func @staticmethod def func(name): print('hello from CommandDispatch.func') for ci in CommandInfo.cmds: if ci.shortname == name or ci.longname == name: return ci.func raise RuntimeError('unknown command') @CommandDispatch(shortname='co', longname='commit') def commit(msg): print('commit msg: {}'.format(msg)) commit('sample commit msg')
Nitin Muppalaneni Mar 02 '17 at 19:28 2017-03-02 19:28
source share