elif alternative

MRAB python at mrabarnett.plus.com
Thu Sep 17 21:55:54 CEST 2009

gert wrote:
> Can anybody show me a better looking alternative for this elif
> structure ?
> http://code.google.com/p/appwsgi/source/browse/appwsgi/wsgi/appointment.wsgi

Where you have cascaded ifs based on a single value, one alternative is
to use a dict where the test value is the key and functions are the

def do_overview():
     db.execute("SELECT calendar,appointment FROM appointments WHERE 
calendar >= ? AND calendar < ?",(v['from'],v['to']))

def do_find():
     db.execute("SELECT users.name, appointments.* FROM users, 
appointments WHERE users.uid = appointments.uid AND 
appointments.calendar >= ? AND appointments.appointment LIKE ? GROUP BY 


actions = {'overview': do_overview, 'find': find, ...}


Your code does have an 'if' which breaks the pattern, but you might be
able to work around it.

More information about the Python-list mailing list