New user's initial thoughts / criticisms of Python

lorenzo.gatti at gmail.com lorenzo.gatti at gmail.com
Mon Nov 11 05:09:11 EST 2013


Regarding the "select" statement, I think the most "Pythonic" approach is using dictionaries rather than nested ifs. 
Supposing we want to decode abbreviated day names ("mon") to full names ("Monday"):
day_abbr='mon'

day_names_mapping={
    'mon':'Monday',
    'tue':'Tuesday',
    'wed':'Wednesday',
    'thu':'Thursday',
    'fri':'Friday',
    'sat':'Saturday',
    'sun':'Sunday'
    }
try:
    full_day_name=day_names_mapping[day_abbr.casefold()]
except KeyError:
    raise GoodLuckFixingItException('We don't have "'+day_abbr+'" in our week')

This style is more compact (usually one line per case) and more meaningful (generic processing driven by separate data) than a pile of if statement, and more flexible: 

full_day_names=('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday')
day_names={x.casefold()[0:3] : x for x in full_day_names}
#

A dict can also contain tuples, lists, and nested dicts, consolidating multiple switches over the same keys and organizing nested switches and other more complex control structures.



More information about the Python-list mailing list