Move dictionary from instance to class level

Anthony Tolle anthony.tolle at gmail.com
Thu Aug 27 09:36:25 EDT 2009


To take things one step further, I would recommend using decorators to
allow symbolic association of functions with the message identifiers,
as follows:

======================================

(MESSAGE_ONE
,MESSAGE_TWO
,MESSAGE_THREE
) = xrange(3)

class MyClass(object):
    method_dict = {}

    # create helper decorator
    register_method = lambda msg, method_dict=method_dict: lambda
function: method_dict.setdefault(msg, function)

    @register_method(MESSAGE_ONE)
    def handle_one(self):
        print 'handling MESSAGE_ONE'

    @register_method(MESSAGE_TWO)
    def handle_two(self):
        print 'handling MESSAGE_TWO'

    @register_method(MESSAGE_THREE)
    def handle_three(self):
        print 'handling MESSAGE_THREE'

    # no longer need helper decorator
    del register_method

    # function to dispatch messages
    def on_message_received(self, msg):
        MyClass.method_dict[msg](self)

x = MyClass()

x.on_message_received(MESSAGE_ONE)
x.on_message_received(MESSAGE_TWO)
x.on_message_received(MESSAGE_THREE)

======================================

Note: the line containing the lambda definition is all one line.



More information about the Python-list mailing list