对于同一个任务,我编写了两个不同的函数。我想知道使用哪个更优雅。
任务是检查pydot
对象是否看到请求的节点,如果是,则返回节点和图形对象。如果节点不存在,则需要创建节点。
为了获取节点的名称,我使用了pydot
objectsget_nodes()
函数。但是,如果还没有引入任何节点,则此函数返回一个空列表。因此,在迭代值之前,我进行了一个空列表检查。
第一个变体('variant1')很容易理解。在长度检查之后,这是必要的node.get_name()
,它循环到节点名称,一旦找到正在搜索的节点,就会返回节点和图。如果没有,它会调用一个函数来创建节点并更新图形。尽管此功能易于理解,但恕我直言,它并不优雅。它看到两个'return'语句:
def variant1(node_name, graph):
if len(graph.get_nodes()) > 0:
for node in graph.get_nodes():
if node_name == node.get_name():
return node, graph
return create_node(node_name, graph)
第二种变体,要复杂得多。一旦在图中找到节点,它就会中断并直接跳转到最后一行('return node, graph')。此变体只有一个 return 语句。
def variant2(node_name, graph):
if len(graph.get_nodes()) > 0:
for node in graph.get_nodes():
if node_name == node.get_name():
break
else:
# the node doesnt exist. create it and update the graph
node, graph = create_node(node_name, graph)
else:
# create the first node in the graph
node, graph = create_node(node_name, graph)
return node, graph
我的问题是,根据“The Zen of Python”、“PEP8”还是“Google Python Style Guide”,我应该更喜欢使用哪一个?