Blame | Last modification | View Log | RSS feed
#!/usr/bin/env python## Copyright 2006, Ira W. Snyder (devel@irasnyder.com)# License: GNU GPL v2 (or, at your option, any later version)## Print structure description:# ===============================================# desc = { TYPE1 : func1, TYPE2 : func2, ... }## Each type will be a unique key (enforced by the dict)# Each func will be a pointer to a function.import errnoclass PrintSystem (object):"""A very generic printing system. This class allows you to specify astructure that describes your printing system, and it will handleany further messages sent to it."""def __init__ (self, description):self.__description = descriptiondef __default_action (self, mytype, mydata):print 'ERROR: no action for: type=%s data=%s' % (str(mytype), str(mydata))def mprint (self, message):"""Print a message according to our description.It should be in the form (TYPE, ...)"""# If there is no type in the message, it must be invalidif len(message) < 1:return -errno.EINVALmytype = message[0] # the first element is the typemydata = message[1:] # the rest is the data# If we don't have a valid function to use, this message# must be invalidif mytype not in self.__description.keys():self.__default_action (mytype, mydata)return -errno.EINVAL# Looks like we're good, call the correct function# with the data giventry:self.__description[mytype](mydata)except:print 'Had an exception while trying to print what appeared to'print 'be a valid message. The message was:'self.__default_action (mytype, mydata)return -errno.EINVAL# We got here, so we completed successfully!return 0################################################################################# Test material is below################################################################################def f1 (data):(a, b, c) = dataprint 'in f1 a=%d b=%d c=%d' % (a, b, c)def f2 (data):(a, b) = dataprint 'in f2 a=%s b=%s' % (a, b)def f3 (data):print 'no data for f3'def main():( TYPE1, TYPE2, TYPE3 ) = range(3)mystruct = { TYPE1 : f1, TYPE2 : f2, TYPE3 : f3 }ps = PrintSystem (mystruct)print 'All here should succeed:'ps.mprint ((TYPE1, 1, 2, 3))ps.mprint ((TYPE2, 'hello', 'world'))ps.mprint ((TYPE3,))ps.mprint ((TYPE1, 2, 3, 4))print '\nShould fail here:'ps.mprint ((20, 'a', 'b', 'c'))if __name__ == '__main__':# Run test codemain ()