python - 避免使用全局变量
问题描述
我正在尝试使用此函数使用模块中的类返回两个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
解决方案
有两种常见的方法可以解决您的问题:将列表作为参数传递和合并递归调用的返回值。
以下是如何将列表作为参数传递。我们创建一个包装函数来隐藏该实现细节。
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
如果你想变得更漂亮,你可以使用生成器,但这对你的代码来说是一个稍微大一点的改变。
推荐阅读
- macos - MAC 上包含/排除命令的 Rsync 问题
- spring-mvc - 我们可以使用单一方法在 Spring REST 中处理 HTTP POST 和 PUT
- php - Zend 框架模型中是否有任何 beforeSave 或 afterSave 方法?
- r - 用于输入信息的绘图生成中间功能
- ubuntu - 运行命令行工具时避免密钥环消息
- c# - 在 C# 中的 ElasticSearch 中编写两个应该条件
- azure - 如何在 AzureFunction 中注册自定义遥测以获得额外的自定义属性
- python - 来自 scikit-garden 的分位数随机森林的预测速度非常慢
- html - 从哈希 ruby on rails select_tag
- firebase - 在 Firebase 中跟踪推送通知(使用 react-native-fcm)