Flatten Nested Try¶
Sourcery refactoring id: flatten-nested-try
¶
Description:¶
Merge nested try-statement into a single try
Before:¶
def testConnection(db, credentials):
try:
try:
db.connect(credentials)
except InvalidCredentials:
return "Check your credentials"
except ConnectionError:
return "Error while trying to connect"
finally:
print("Connection attempt finished")
return "Connection Successful"
After:¶
def testConnection(db, credentials):
try:
db.connect(credentials)
except InvalidCredentials:
return "Check your credentials"
except ConnectionError:
return "Error while trying to connect"
finally:
print("Connection attempt finished")
return "Connection Successful"
Explanation:¶
Flattening try-except statements nested within a try-finally generates equivalent code that is easier to read and expand upon.