Why this matters
Using or/and with exceptions in except blocks doesn’t work as expected and can lead to unintended behavior. Use tuples instead.
except StatementsDetect except clauses that use or or and to catch multiple exceptions. This does not work as intended. Recommend using a tuple of exceptions instead.
Using or/and with exceptions in except blocks doesn’t work as expected and can lead to unintended behavior. Use tuples instead.
Side-by-side examples engineers can pattern-match during review.
try:
raise TypeError()
except ValueError or TypeError: # Noncompliant
print("Catching only ValueError")
except ValueError and TypeError: # Noncompliant
print("Catching only TypeError")
except (ValueError or TypeError) as exception: # Noncompliant
print("Catching only ValueError")
foo = ValueError or TypeError # foo == ValueError
foo = ValueError and TypeError # foo == TypeErrortry:
raise TypeError()
except (ValueError, TypeError) as exception:
print("Catching ValueError and TypeError")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.