Skip to content

Instantly share code, notes, and snippets.

@xtream1101
Last active June 20, 2017 20:56
Show Gist options
  • Save xtream1101/fe3fd591669311dd2fea9310856554eb to your computer and use it in GitHub Desktop.
Save xtream1101/fe3fd591669311dd2fea9310856554eb 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