Incorrectly using or in exception handling

Catch multiple exception types using a tuple, not by specifying or.

Using or in exception handler is valid Python insofar as the python parser does not complain, but using or to specify multiple exception classes does not do what you think it should. Take this code as example:

This will only catch ValueError. TypeError will not be caught because Python is treating the ValueError or TypeError as a binary comparison to evaluate rather than as a list of exception classes to catch. Python evaluates ValueError or TypeError to ValueError because ValueError is truthy.

To have Python catch multiple exception types instead specify the multiple types as a tuple:

If our GitHub code review bot spots this issue in your pull request it gives this advice:

code-review-doctorbotsuggested changes just now
except ValueError or TypeError:
Suggested changes
except ValueError or TypeError:
except (ValueError, TypeError):
Commit suggestion

Catch multiple exception types using a tuple, not by specifying or.

Read more
We're your Python code review copilot. Get code improvements right in your pull request with our GitHub code review bot.

Configuring this check

Code Review Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code exception-handler-or in your pyproject.toml file.

Read more about configuring Code Review Doctor.