Move dictionary from instance to class level

Anthony Tolle anthony.tolle at
Thu Aug 27 15:36:25 CEST 2009

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


) = 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)

    def handle_one(self):
        print 'handling MESSAGE_ONE'

    def handle_two(self):
        print 'handling MESSAGE_TWO'

    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):

x = MyClass()



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

More information about the Python-list mailing list