[英]What's a good way to handle shadowing variables?
什么是處理輔助函數中自然與外部變量同名的變量的好方法? 就像在這里我添加了下划線一樣。
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
當然,沒有下划線它也可以工作,但我聽說像這樣隱藏變量是不衛生的。 下划線很丑陋並且容易出錯(可以說比陰影本身更嚴重)。
我建議只是消除不必要的變量,而不是想出給它們類似但不同的名稱的方案。 特別是, 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
更好的名稱(不幸的是,我對這段代碼實際上在做什么沒有足夠好的理解來提出一個描述性的名稱)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.