Enforce conditional values are booleans
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Feature
A rule enforcing the strict use of boolean expressions in an if statement. It should be added to the "Miscellaneous strictness flags".
strict_conditional
TYPE:
boolean
DEFAULT:
False
Enables or disables strict conditional checks. If True, `mypy` only allows boolean expressions in conditional expressions.
Pitch
I've encountered many hard-to-trace bugs due to non-boolean expressions used in conditionals. For instance, lists, containers, objects, or some literals being checked directly.
if [1,2,3]: # list is not a boolean value, will be treated as False if list is empty or None
...
if "Hello world": # str is not a boolean value, will be treated as False if string is empty or None
...
if None: # not a boolean, will be treated as False if None
...
if 2: # not a boolean, might be treated as false if it equals 0
...
Very often, the developer's intention was to perform a null-check, or sometimes, an emptiness check, but this syntax yields potential edge cases where the developer did not intend the conditional to yield False.
With strict_conditional enabled, all of the above scenarios should be flagged.
The below examples naturally should always be valid as the expression yields a boolean value.
if x < 0:
...
if isinstance(x, int):
...
if True:
...
if [1,2,3] is None:
....
if len({}) == 0:
....
This enforces explicit coding practices and better shows the intent of the developer.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by locating mypy's conditional-expression checking and the configuration handling for the "Miscellaneous strictness flags". Add the proposed strict_conditional option with a False default, enforce boolean-only conditional expressions when enabled, and cover the listed valid and invalid cases with tests.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100