Why this matters
Forgetting to close resources like files or sockets can lead to memory leaks or unexpected behavior. The `with` statement ensures resources are properly released, even if an error occurs.
Ensure that resources such as files, sockets, or database connections are managed using the `with` statement. Code that explicitly calls `.close()` without `with` should be refactored to use context managers for automatic resource cleanup.
Forgetting to close resources like files or sockets can lead to memory leaks or unexpected behavior. The `with` statement ensures resources are properly released, even if an error occurs.
Side-by-side examples engineers can pattern-match during review.
file = open('test.txt', 'r')
data = file.read()
file.close()with open('test.txt', 'r') as file:
data = file.read()file = open('test.txt', 'r')
data = file.read()
file.close()with open('test.txt', 'r') as file:
data = file.read()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.