In Python, the try/except/finally construct is commonly used to ensure cleanup actions, such as closing files. Traditionally, Python allowed control flow statements like return, break, or continue inside a finally block, even though this could override behavior from the try or except sections.
Since Python 3.14, the SyntaxWarning is emitted when a control flow statement is used in the finally block, highlighting a pattern that can easily lead to subtle bugs. Consider the following function that attempts to save data to a file and return a success flag:
def save_file(data, path):
f = open(path, 'a')
try:
f.write(data)
except:
return False
finally:
f.close()
return True
print(save_file('Hello', 'test.txt')) # True
print(save_file(123, 'test.txt')) # True
Example will output:
.../intro.py:9: SyntaxWarning: 'return' in a 'finally' block
return True
The return True inside the finally block overrides any return value from the try or except clauses. Even when an exception occurs (such as writing an integer to a file), the function still returns True, masking the error entirely.
The example can be fixed by reserving the finally block strictly for cleanup logic and moving control flow decisions elsewhere:
def save_file(data, path):
f = open(path, 'a')
try:
f.write(data)
return True
except:
return False
finally:
f.close()
print(save_file('Hello', 'test.txt')) # True
print(save_file(123, 'test.txt')) # False
Leave a Comment
Cancel reply