Skip to main content
 首页 » 编程设计

Python编码风格——多重返回语句

2025年05月04日14insus

<分区>

对于同一个任务,我编写了两个不同的函数。我想知道哪个用起来更优雅。

任务是检查 pydot 对象是否看到请求的节点,如果是,则返回节点和图形对象。 如果该节点不存在,则需要创建该节点。

为了获取节点的名称,我使用了 pydot 对象的 get_nodes() 函数。但是,如果尚未引入任何节点,此函数将返回一个空列表。因此,在迭代这些值之前,我进行了一次空列表检查。

第一个变体 ('variant1') 很容易理解。在长度检查之后(由于 node.get_name() 是必需的),它会循环到节点名称,一旦找到正在搜索的节点,就会返回节点和图形。如果不是,它会调用一个函数来创建节点并更新图形。虽然这个功能很容易理解,恕我直言,它并不优雅。它看到两个“返回”语句:

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')。此变体只有一个返回语句。

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”,我应该更喜欢使用哪一个?