-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Enforce conditional values are booleans #16734
Comments
It's not a bad idea to have available in the ecosystem in general. I just question if mypy (or any static type checker) is the best place to enforce programming style rules. Don't any of the other established tools: e.g. Ruff, Black, Pylint, Pycodestyle (formerly pep8) already have a rule for this (or a similar rule in line with PEP8 / or Google's Python style guide )? |
I've looked around and genuinely couldn't find a thing. I created a similar issue for
I would argue that This rule does two things essentially:
The second point is indeed more of a bugbear type of situation, but the first could be seen as some sort of strictness flag related to None values. |
This isn't practical to do outside a type checker, as correctly noted on the Ruff issue. So this is indeed the correct place to request this feature. Mypy already does a subset of what you ask for by e.g. warning when using a function in a boolean context (https://mypy.readthedocs.io/en/stable/error_code_list.html#check-that-function-isn-t-used-in-boolean-context-truthy-function). Warning for all non-booleans in a boolean context is too disruptive and too much against standard Python conventions to turn on by default or even in |
Agreed, it shouldn't be enabled by default. |
(renamed the issue to avoid confusion with #8363) |
Oh, cool, interesting to see the discussion in that particular issue. |
Feature
A rule enforcing the strict use of boolean expressions in an if statement. It should be added to the "Miscellaneous strictness flags".
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.
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.
This enforces explicit coding practices and better shows the intent of the developer.
The text was updated successfully, but these errors were encountered: