Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save codenameyau/8c4e47fa60e23ca2defc5d1feba1c30e to your computer and use it in GitHub Desktop.
Save codenameyau/8c4e47fa60e23ca2defc5d1feba1c30e to your computer and use it in GitHub Desktop.
Python multiple Try/except flat design
# 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
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment