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

后端 未结 4 1933
独厮守ぢ
独厮守ぢ 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:34

    Pylint was failing for my code and research led me to this post:

    ../filename.py:49:11: C1801: Do not use `len(SEQUENCE)` to determine if a sequence is empty (len-as-condition)
    ../filename.py:49:34: C1801: Do not use `len(SEQUENCE)` to determine if a sequence is empty (len-as-condition)
    

    This was my code before:

    def list_empty_folders(directory):
    """The Module Has Been Build to list empty Mac Folders."""
    for (fullpath, dirnames, filenames) in os.walk(directory):
        if len(dirnames) == 0 and len(filenames) == 0:
            print("Exists: {} : Absolute Path: {}".format(
                os.path.exists(fullpath), os.path.abspath(fullpath)))
    

    This was after my code fix. By using the int() attribute, I seem to have satisfied the Pep8/Pylint and doesn't seem to have a negative impact on my code:

    def list_empty_folders(directory):
    """The Module Has Been Build to list empty Mac Folders."""
    for (fullpath, dirnames, filenames) in os.walk(directory):
        if len(dirnames).__trunc__() == 0 and len(filenames).__trunc__() == 0:
            print("Exists: {} : Absolute Path: {}".format(
                os.path.exists(fullpath), os.path.abspath(fullpath)))
    

    My Fix

    By adding .__trunc__() to the sequence it seems to have settled the need.

    I do not see a difference in the behaviour, but if anyone knows specifics that I am missing, please let me know.

提交回复
热议问题