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

    Join Date
    Aug 2012
    Posts
    4
    Rep Power
    0

    Handling optional parameters if/else vs try/except


    Hi folks,

    I'm wondering about which is considered in terms of good coding practice, using conditional statements to handle optional parameters with sys.argv or using try/except. I know there are fancier ways, like argparse. But I'm trying to keep it v. simple at this point.

    Here's an example of what I'm talking about that handles one (optional) argument. You could do this

    Code:
    if len(sys.argv) == 2:   
        x = sys.argv[1] 
    else:   
        x= "default value"
    #do stuff with x
    or you could do this

    Code:
    try:   
        x = sys.argv[1] 
    except IndexError:   
        x = "default value"
    #do stuff with x
    of course, you could also do...
    Code:
    x= "default value"
    if len(sys.argv) == 2:   
        x = sys.argv[1] 
    #do stuff with x
    shorter code, but it seems less transparent.

    Thanks!
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,850
    Rep Power
    481
    Sometimes this also works:
    x = (sys.argv+['default value'])[1]

    python.org people recommend the
    try:
    except:
    method if you expect the exceptions are rare.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2011
    Posts
    139
    Rep Power
    4

    Error Handling


    I have used the try/except method to trap errors having been input by users. for example, if the code looks for a nonexistent file, it will jump to the 'except' and keep running, rather than stop running while displaying an error.
    Last edited by WynnDeezl; August 2nd, 2012 at 12:25 PM.

IMN logo majestic logo threadwatch logo seochat tools logo