17.8.09

A Python dispatcher pattern


import sys
## the format of the dictionary is as follows:
## 'command': {'sub command' :
## {'function':'module.class.function'}
## }
dispatchDictionary = {
'add' : {'friend' :
{'function':'core.friends.friends.addFriend', 'help':'blah'}},
'connection' : {'info':{'function':'core.class.function','help': 'prints help'},
'help' : {'function' : 'core.shell.help.print_help'}},
'list' : {'files' : {'function' : 'core.shell.file.f_list'}},
'get' : {'file' : {'function' : 'core.shell.file.f_get'}}
}

class dispatch:
def __init__(self):
pass

def dispatch(self, input):
## the values 'in' _should_ be a list ['hi', 'hi']
try:
value = reduce(dict.get, input[:-1], dispatchDictionary)
except (TypeError), e:
## empty
print e
return

key = input[-1:][0]
try:
## make sure it really exists
value[key]
except KeyError:
key = input[:-1][0]


if key not in value:
if 'function' not in value:
## no function key
return
if value['function'] is None:
## empty
return
self.execute(value['function'], input)

elif key in value:
if 'function' not in value[key]:
## no function key
print value[input[-1:]]
return
if value[key]['function'] is None:
## empty
return
self.execute(value[key]['function'], input)



def execute(self, command, input):
if not input[-1:][0][:1] == '[' and not input[-1:][0][-1:] == ']':
formatted = False
else:
formatted = True

cSplit = command.split('.')
try:
__import__(cSplit[:1][0])
except ImportError, e:
print e
try:
module = sys.modules[cSplit[:1][0]]
except Exception, e:
print e
return

if formatted:
splittable = input[-1:][0][1:-1]
funcInput = splittable.split('/')
else:
funcInput = input[1:]

## create an instance
Class = self.r_getattr(module, '.'.join(cSplit[1:-1]))
c = Class()
func = self.r_getattr(c, '.'.join(cSplit[-1:]))
func(funcInput)

def r_getattr(self, object, attr):
return reduce(getattr, attr.split('.'), object)

def r_setattr(self, object, attr, value):
attrs = attr.split('.')
return setattr(reduce(getattr, attrs[:-1], object), attrs[-1], value)

def add(self):
pass


No comments:

Post a Comment