首页 > 解决方案 > 避免使用全局变量

问题描述

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

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

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

作为参考,函数以相同的方式递归,但它们跟踪一组不同的数据,例如需要拆分为same_leftpath_list和的 same_files same_rightpath_list

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

标签: pythonpython-2.7

解决方案


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

以下是如何将列表作为参数传递。我们创建一个包装函数来隐藏该实现细节。

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

如果你想变得更漂亮,你可以使用生成器,但这对你的代码来说是一个稍微大一点的改变。


推荐阅读