for...else

Laura Creighton lac at openend.se
Tue Jun 2 10:29:50 EDT 2015


You may be looking for dictionary dispatching.

You can translate the key into a callable.

def do_ping(self, arg):
    return 'Ping, {0}!'.format(arg)

def do_pong(self, arg):
    return 'Pong, {0}!'.format(arg)

dispatch = {
    'ping': do_ping,
    'pong': do_pong
	}

and then at some point do

    dispatch[command](arg)

It is useful to know that tuples make perfectly good dictionary keys,
in case you need to store more state somewhere.

Laura



More information about the Python-list mailing list