basedpyright icon indicating copy to clipboard operation
basedpyright copied to clipboard

Enforce conditional values are booleans

Open npip99 opened this issue 1 year ago • 4 comments

Same issue as https://github.com/python/mypy/issues/16734

When a developer does if var: to check whether or not a var is None, then the if condition implicitly holds for empty strings or the integer "0". This is virtually always a bug, and is essentially never intentional. We should mark this as an error, in order to have users explicitly do if var is not None:.

This is also recommended by PEP8

npip99 avatar Oct 09 '24 02:10 npip99

Edge-case for some users: -> I know that some people do actually like doing if var: for checking if a collection is non-empty. IMO even if people want to do this, it shouldn't be allowed for variables that are optional, because then the if statement is conflating a None check with an emptiness check.

The version that I would want would never allow even this, but rather force users to do if len(var) == 0: to check for emptiness. But, it should probably be a configuration option that people can disable.

npip99 avatar Oct 09 '24 02:10 npip99

i like this idea. eslint has a rule for this too

DetachHead avatar Oct 09 '24 03:10 DetachHead

although, when it's unambiguous (there is no truthyness overlap between the multiple entries in the union), it's not really a problem

class A:
    def __bool__(self) -> True:
        return True
a: A | None
if a:
    ...

KotlinIsland avatar Oct 09 '24 04:10 KotlinIsland

I have my own set of things that are acceptable in a conditional expression: bool, int, None, and objects that don't (and are not reasonably expected to) override the default object.__bool__

So I would like this to be configurable with such options.

beauxq avatar Oct 09 '24 16:10 beauxq