[clang] [lldb] [llvm] [openmp] [polly] fix(python): fix comparison to True/False (PR #91858)

DonĂ¡t Nagy via llvm-commits llvm-commits at lists.llvm.org
Wed May 15 03:37:31 PDT 2024


NagyDonat wrote:

The main problem with comparison to `True`/`False` is that it's completely redundant when the variable is _guaranteed to be boolean_. However, if a variable may contain either a boolean or something else, it's reasonable to compare it with `True` or `False`.

For the operator `==` there is another pitfall that according to Python `True == 1` and `False == 0` holds. (In ancient versions `True` and `False` were simply integer constants with these values; now `bool` is a subclass of `int` and preserves this old behavior.)

This implies that:
- When `x` is guaranteed to be a boolean, it should be used as `if x:` or `if not x:` (instead of `if x == True:` or `if x == False:`.
- Otherwise it may be reasonable to use the `is` operator: e.g. when `x` may be `True`, `False` or `None`, it is reasonable to check `if x is False:` or `if x is None:`.
- Using `==` has no advantage over `is` and could cause very surprising bugs when the variable can hold either a boolean or a number, so I'd say that it should be avoided. (However I admit that when `x` is known to be either `True`, `False` or `None`, there's a high chance that I'd instinctively write `if x == False:`.)

https://github.com/llvm/llvm-project/pull/91858


More information about the llvm-commits mailing list