避免使用全局变量

时间:2018-06-13 02:30:31

标签: python python-2.7

我正在尝试使用此函数使用dircmp模块中的类filecmp返回两个列表。

我需要在我的代码中使用在多个不同部分生成的列表,现在我已经通过使列表成为全局变量来实现这一点。

我想知道是否有一个解决方案可以在函数完成后通过子目录返回完全追加的两个列表。这样我就不需要通过我的代码继续为每个函数创建全局变量。

作为参考,函数以相同的方式递归,但它们跟踪不同的数据集,例如需要分成same_leftpath_listsame_rightpath_list的same_files。

diff_leftpath_list = []
diff_rightpath_list = []

def print_diff_files(dcmp):

    for name in dcmp.diff_files:
        print("[Differing File] '%s' found in %s and %s" % (name, dcmp.left, 
                                                      dcmp.right))
        diff_leftpath = os.path.join(dcmp.left, name)
        diff_rightpath = os.path.join(dcmp.right, name)
        diff_leftpath_list.append(diff_leftpath)
        diff_rightpath_list.append(diff_rightpath)

    for sub_dcmp in dcmp.subdirs.values():
        print_diff_files(sub_dcmp)

print_diff_files(dcmp)
print diff_leftpath_list

1 个答案:

答案 0 :(得分:0)

解决问题的方法有两种:将列表作为参数传递,并合并递归调用的返回值。

以下是您可以将列表作为参数传递的方法。我们创建一个包装器函数来隐藏实现细节。

def print_diff_files(dcmp):
    """calls the wrapper to do the real work.  Hides the list management."""
    left = []
    right = []
    _print_diff_files_impl(dcmp, left, right)
    return left, right

def _print_diff_files_impl(dcmp, diff_leftpath_list, diff_rightpath_list):
    for name in dcmp.diff_files:
        print("[Differing File] '%s' found in %s and %s" % (name, dcmp.left, 
                                                      dcmp.right))
        diff_leftpath = os.path.join(dcmp.left, name)
        diff_rightpath = os.path.join(dcmp.right, name)
        diff_leftpath_list.append(diff_leftpath)
        diff_rightpath_list.append(diff_rightpath)
    for sub_dcmp in dcmp.subdirs.values():
        _print_diff_files_impl(sub_dcmp, diff_leftpath_list, diff_rightpath_list)

以下是使用返回值管理它的方法。这通常是一种更好的方法。

def print_diff_files(dcmp):
    left = []
    right = []
    for name in dcmp.diff_files:
        print("[Differing File] '%s' found in %s and %s" %
              (name, dcmp.left, dcmp.right))
        diff_leftpath = os.path.join(dcmp.left, name)
        diff_rightpath = os.path.join(dcmp.right, name)
        left.append(diff_leftpath)
        right.append(diff_rightpath)
    for sub_dcmp in dcmp.subdirs.values():
        new_left, new_right = print_diff_files(sub_dcmp)
        left.extend(new_left)
        right.extend(new_right)
    return left, right

如果你想获得更好的产品,你可以使用发电机,但这对你的代码来说是一个稍大的变化。