switch

Tim Chase python.list at tim.thechases.com
Wed Dec 9 20:57:48 CET 2009


Carl Banks wrote:
> What if the object is a string you just read from a file?
> 
> How do you dispatch using polymorphism in that case?

This is where I most miss a switch/case statement in Python...I 
do lots of text-file processing (cellular provider data), so I 
have lots of code (for each provider's individual format) that 
looks like

   phones = {}
   for row in csv.DictReader(file('data.txt', 'rb')):
     phonenumber = row['phonenumber']
     if phonenumber not in phones:
       phones[phonenumber] = Phone(phonenumber)
     phone = phones[phonenumber]
     rectype = rectype
     if rectype == '01':
       phone.international += Decimal(row['internationalcost'])
     elif rectype == '02':
       phone.text_messaging += (
         int(row['textmessages sent']) +
         int(row['pages received']) +
         int(row['textmessages sent']) +
         int(row['pages received'])
     elif rectype == ...
        ...
     else:
       raise WhatTheHeckIsThis()

which would nicely change into something like

   switch row['recordtype']:
     case '01':
       phone.international += Decimal(row['internationalcost'])
       // optionally a "break" here depending on
       // C/C++/Java/PHP syntax vs. Pascal syntax which
       // doesn't have fall-through
     case '02':
       phone.text_messaging += (
         int(row['textmessages sent']) +
         int(row['pages received']) +
         int(row['textmessages sent']) +
         int(row['pages received'])
     ...
     default:
       raise WhatTheHeckIsThis()

This doesn't convert well (i.e. compactly) to a 
dictionary-dispatch idiom. :(

-tkc







More information about the Python-list mailing list