Try, try again - Multiple try/except blocks in a flat format

Snippet

data = {'some_key': 'key value'}
key_data = None
for _ in range(1):
    try:
        key_data = data['someKey']
    except Exception: pass
    else: break  # It worked

    try:
        key_data = data['some_key']
    except Exception: pass
    else: break  # It worked

    try:
        key_data = data['key?']
    except Exception: pass
    else: break  # It worked
        
    # Nothing above worked
    print("Nothing Worked")
    
print(key_data)

# I know dict's have `.get()`, this example was made to break if the key is not
#   there to show the use of multiple try/except's
# Yes I know that having the except and else on 1 line each does not fit with PEP8 standards.
# But when you have many of them it helps reduce the size of the file and is no harder to read

Description

This was created long ago after seeing a co-worker create a deep nested set of try/except blocks while trying to extract some data from a website. I understood the reason of trying many different ways, but I did not like how nested the python code got because of it, so I created this flat try/except instead.

By xtream1101 Updated 2025-02-06 13:43