Why is the use of len(SEQUENCE) in condition values considered incorrect by Pylint?

后端 未结 4 1894
独厮守ぢ
独厮守ぢ 2021-01-30 08:08

Considering this code snippet:

from os import walk

files = []
for (dirpath, _, filenames) in walk(mydir):
    # More code that modifies files
if len(files) == 0:         


        
4条回答
  •  故里飘歌
    2021-01-30 08:10

    When is the use of len(SEQ) as a condition value problematic? What major situations is Pylint attempting to avoid with C1801?

    It’s not really problematic to use len(SEQUENCE) – though it may not be as efficient (see chepner’s comment). Regardless, Pylint checks code for compliance with the PEP 8 style guide which states that

    For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

    Yes: if not seq:
         if seq:
    
    No:  if len(seq):
         if not len(seq):
    

    As an occasional Python programmer, who flits between languages, I’d consider the len(SEQUENCE) construct to be more readable and explicit (“Explicit is better then implicit”). However, using the fact that an empty sequence evaluates to False in a Boolean context is considered more “Pythonic”.

提交回复
热议问题