Flatten Nested Try
Documentation Index
Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
Use this file to discover all available pages before exploring further.
Sourcery refactoring id: flatten-nested-try
Section titled “Sourcery refactoring id: flatten-nested-try”Description:
Section titled “Description:”Merge nested try-statement into a single try
Before:
Section titled “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:
Section titled “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:
Section titled “Explanation:”Flattening try-except statements nested within a try-finally generates equivalent code that is easier to read and expand upon.