【发布时间】:2022-01-27 11:54:21
【问题描述】:
在帮助函数中处理与外部变量同名的变量的好方法是什么?就像在这里我添加了下划线一样。
from typing import List, Set, Any, Tuple, Callable
def graph_fold(g: Graph,
combiner: Callable[[Node_key, List], Any]) -> List:
"""Equivalent to forming a depth-first forest and
mapping `fold-tree combiner` over
the trees"""
def helper(_disc: Set[Node_key], node: Node_key) -> Tuple[Any, Set[Node_key]]:
_disc.add(node)
_xs = []
for nbr in get_nbrs(g, node):
if nbr not in _disc:
_x, _disc = helper(_disc, nbr)
_xs.append(_x)
return combiner(node, _xs), _disc
disc = set()
xs = []
for v in vertices(g):
if v not in disc:
x, disc = helper(disc, v)
xs.append(x)
return xs
当然,没有下划线也可以,但我听说像这样隐藏变量是不卫生的。下划线很难看并且容易出错(可以说比阴影本身更严重)。
【问题讨论】:
-
您能举例说明使用下划线可能导致的错误吗?如果使用完全不同的变量名称是不可能的(?),并且您不希望使用或不使用下划线来隐藏名称,那么也许可以考虑将辅助函数移到父函数之外,但这意味着手动传递所有vars 作为参数
-
在参数名称中使用下划线通常表示该参数没有在实现中使用(即它只是为了满足特定的签名)。以这种方式使用它是令人困惑的。
-
@IainShelvington 当你的意思是非下划线版本时使用下划线版本,反之亦然是一个潜在的错误。我正在考虑一般情况,当我想在函数内部重复一个操作时,我对其执行操作的变量自然会与内部函数中的相应参数具有相同的名称。也许这种情况在 Python 中并不经常出现,也许人们以不同的方式处理它?
标签: python functional-programming graph-theory naming