The optional comparetozero
extension to pylint checks for any comparison to 0
and flags it. It is unclear to me why this is bad to do.
According to the docstring of the comparetozero
module,
Most of the times you should use the fact that integers with a value of 0 are false.
An exception to this rule is when 0 is allowed in the program and has a different meaning than None!
What exactly does this mean?
My understanding of the above is that it means that you should not do something like
def return_false():
return False
if return_false() == 0:
pass
because that is abusing the falsy nature of 0
, but that it is okay to do
if foo % 4 == 0:
pass
because you are comparing two integers to see if they are both literally zero.
If my understanding is correct, is it better to make specific # pylint: disable
statements for the instances where you are literally checking if a value is zero, or what?
Pythonic way of comparison is to use implicit boolean checks or truthy values. For e.g.
some_val = 0
if some_val == 0: # non-pythonic way to check
vs
if not some_val: # 0 is false for python and hence a boolean way is easier to read
Its better coding practice to say "If this is not true" and the truthy value of a variable is based on various forms such as an empty list, or empty string
So all in all, the following reads better:
some_str = ''
if not some_str: # better than if some_str == ''
some_number = 0
if not some_number: # better than if some_number == 0
some_list = []
if not some_list: # better than if len(some_list) == 0