0

I do this error handling a lot, is there a shorter way of writing this try except block ?

        try:
            config = item['asset'][0]['config']
        except:
            config = 'None'

like a pythonic oneliner maybe ?

Victor
  • 427
  • 1
  • 6
  • 19
  • 1
    What is your error that gets thrown? You might be able to just check for the error like a one line if statement so that you don't try to access that element of `item` on the event that it won't work. Something like `config = item['asset'][0]['config'] if else config = 'None'` – Davy M Oct 26 '17 at 21:16
  • Iam looking at a large data source and I have such indexing and dict lookup all over and many times i dont find values and Iam allowed to fill 'None' for those so Iam looking for a oneliner – Victor Oct 26 '17 at 21:19

1 Answers1

0

Why don't you just write a method for it so you can call it whenever you need?

def validate_item(item):
    try:
        config_letter = item['asset'][0]['config']
    except:
        config_letter = 'None'

Obviously this is just a rough outline so you can reformat the params however you need.

  • 1
    Probably return config_letter in case it's not a global variable; that way the call could look like: `config_letter = validate_item(item)` – Davy M Oct 26 '17 at 21:19
  • I cant afford to do that, thats much many more lines. There must be a oneliner for the above – Victor Oct 26 '17 at 21:20
  • 2
    If the way you're doing it now is writing a try/except block every time you need to verify it, how is this more lines? –  Oct 26 '17 at 21:22