Why this matters
Failing to close files, sockets, or other resources can cause memory leaks and unexpected behavior. Placing cleanup code in a finally block ensures resources are always released, even if an error occurs.
finally BlocksCheck if resources such as files or database connections are properly closed in a finally block. This ensures resources are always released, even if an exception occurs.
Failing to close files, sockets, or other resources can cause memory leaks and unexpected behavior. Placing cleanup code in a finally block ensures resources are always released, even if an error occurs.
Side-by-side examples engineers can pattern-match during review.
file = open('test.txt')
data = file.read()try:
file = open('test.txt')
data = file.read()
finally:
file.close()From the same buckets as this rule.
Check if loops use equality operators (== or !=) in termination conditions. These can lead to infinite loops if the condition is never met exactly. Instead, use relational operators like < or > for safer loop termination.