新手问题 - 将功能分为两个



所以我是Python的新手,我的功能需要分为两个部分。以前这是一个功能,但是经过一个比我更了解方式的建议之后,我得到的提示说我的功能做得太多了,我需要将其分解为两个单独的事情。所以我在这里。

以下是分为两个部分的代码。

我想知道我是否必须在这两个功能中提及pathlist

应该做的是检查文件是否存在,然后如果它们确实运行第二个功能以删除实际目录。

def check_directory(pathslist):
    for path in pathslist:
        if os.path.exists(path) and os.path.isdir(path):
            remove_directory(pathslist)
dirs_to_delete = [
    'C:MyDirectoryPath1',
    'C:MyDirectoryPath2',
    'C:MyDirectoryPath3'
 ]
def remove_directory(pathslist):
    for path in pathslist:
        if os.path.exists(path) and os.path.isdir(path):
            shutil.rmtree(path)
            print(colored('Found ' + path + ' removing', 'green'))

不完全是。如果您将整个路径清单传递给remove_directory,则无论是否存在它,您都将尝试删除每个路径,这使您的check_directory函数不必要。我认为您的意思是您的check_directory函数,只通过存在的路径删除__directory:

def check_directory(pathslist):
    for path in pathslist:
        if os.path.exists(path) and os.path.isdir(path):
            remove_directory(path)
dirs_to_delete = [
    'C:MyDirectoryPath1',
    'C:MyDirectoryPath2',
    'C:MyDirectoryPath3'
 ]

def remove_directory(path):
     shutil.rmtree(path)
     print(colored('Found ' + path + ' removing', 'green'))

您可能想尝试为您编写的每个函数编写评论,以描述它的作用。第二个使用"one_answers"或一个其他动词一词,这可能是您最好将函数分为多个部分(这只是经验法则,而不是绝对的)。此外,您需要避免重复代码 - 如果您在两个单独的功能中具有相同的代码行,那是您需要重新考虑设计的另一个提示。

编辑:正如评论中指出的那样,您写的方式表示,如果存在,请致电check_directory将删除该目录。除了想要删除它以外的原因外,似乎有人会打电话给check_directory,这似乎是合理的,您最好使用remove_directory调用check_directory,而不是相反:

    def check_directory(path):
         # returns true if path is an existing directory
         return os.path.exists(path) and os.path.isdir(path)
    def remove_directory(pathlist):
        for path in pathlist:
            if check_directory(path):
                shutil.rmtree(path)
                print(colored('Found ' + path + ' removing', 'green'))

最新更新