Considering this code snippet:
from os import walk
files = []
for (dirpath, _, filenames) in walk(mydir):
# More code that modifies files
if len(files) == 0: # <-- C1801
return None
I was alarmed by Pylint with this message regarding the line with the if statement:
[pylint] C1801:Do not use
len(SEQUENCE)
as condition value
The rule C1801, at first glance, did not sound very reasonable to me, and the definition on the reference guide does not explain why this is a problem. In fact, it downright calls it an incorrect use.
len-as-condition (C1801): Do not use
len(SEQUENCE)
as condition value Used when Pylint detects incorrect use of len(sequence) inside conditions.
My search attempts have also failed to provide me a deeper explanation. I do understand that a sequence's length property may be lazily evaluated, and that __len__
can be programmed to have side effects, but it is questionable whether that alone is problematic enough for Pylint to call such a use incorrect. Hence, before I simply configure my project to ignore the rule, I would like to know whether I am missing something in my reasoning.
When is the use of len(SEQ)
as a condition value problematic? What major situations is Pylint attempting to avoid with C1801?
if files:
orif not files:
len
doesn't know the context in which it is called, so if computing the length means traversing the entire sequence, it must; it doesn't know that the result is just being compared to 0. Computing the boolean value can stop after it sees the first element, regardless of how long the sequence actually is. I think pylint is being a tad opinionated here, though; I can't think of any situation where it is wrong to uselen
, just that it's a worse option than the alternative.