#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0

    "if" Alternative


    I'm parsing an inputed string for commands, and I was wondering if there is a better way to associate the inputed commands with their action than just using ifs

    i.e.
    Code:
    if command == 'foo':
            doStuff()
    if command == 'bar':
            foo = 0
            doMoreStuff()
    
    ...
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    Yes there is - use a dispatch table. e.g.

    Code:
    dispatchTable = { 
        'foo' : doStuff,
        'bar' : doMoreStuff,
        #etc
    }
    
    dispatchTable[command]()
    This does have some limitations - each of your actions must be packed into separate functions. In your original code the 'bar' command sets foo=0 before the call to doMoreStuff, which would not be possible using this technique.

    Sadly Python does not have anonymous code blocks, which would make this technique more powerful. You could possibly simulate it using eval and the compiler module, but it would probably be more trouble than it is worth.

    Regards,

    Dave - The Developers' Coach
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Posts
    325
    Rep Power
    12
    Dave's way is the python way alternative to the switch statement.

    If you're looking for switch, it was intentionally left out of python for the same reasons as removing +=,-=,etc .. as well as leaving out a host of other things such as condition?ret_true:ret_false.

    Python maintains the highest clarity (as far as code readability goes) as well as removing possible causes of bugs. Alot of ppl forget about the break in switch statements which causes alot of bugs. Also if/elif/else is the clearest code for the job as far as readability goes..
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    217
    Rep Power
    0
    It's it just me or do '+=' and '-=' work? I'm guessing you mean the increment and decrement operators (++ and --).
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Posts
    325
    Rep Power
    12
    ah crap .. yeh that's wot I meant =P

IMN logo majestic logo threadwatch logo seochat tools logo