【问题标题】:What's a good way to handle shadowing variables?处理阴影变量的好方法是什么?
【发布时间】: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


【解决方案1】:

我建议只是消除不必要的变量,而不是想出给它们起相似但不同的名称的方案。特别是,disc 不需要作为参数传递并返回,因为只有一个 disc(它是可变的,所以它永远不需要重新分配)。一旦你摆脱了disc 的所有额外传递/重新分配,你也可以在循环中摆脱x,你可以通过使其成为列表理解来摆脱xs

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"""
    disc = set()

    def helper(node: Node_key) -> Any:
        disc.add(node)
        return combiner(node, [
            helper(nbr)
            for nbr in get_nbrs(g, node)
            if nbr not in disc
        ])

    return [
        helper(v)
        for v in vertices(g)
        if v not in disc
    ]

我还建议给helper 起一个比helper 更好的名称(不幸的是,我对这段代码的实际作用并没有足够的了解,无法给出一个描述性的名称)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 2013-02-25
    • 2010-10-14
    • 2011-07-19
    • 1970-01-01
    • 2016-06-12
    相关资源
    最近更新 更多